1/12
BTech 1st Year ยท Computer Science ยท C++ Programming

Objects & Classes in C++

The Foundation of Object-Oriented Programming

class Student { public: string name; void study(); };
Press โ†’ or click to navigate
02

What We'll Cover

01
OOP Concepts Why OOP? Core principles
02
Classes Defining & structuring classes
03
Objects Creating & using objects
04
Access Specifiers public, private, protected
05
Constructors Default, parameterized, copy
06
Member Functions Methods & this pointer
03

What is OOP?

Object-Oriented Programming is a paradigm that organizes software design around data (objects) rather than functions and logic.

๐Ÿ”’
Encapsulation
๐Ÿงฌ
Inheritance
๐Ÿ”„
Polymorphism
๐ŸŽญ
Abstraction
Real World Analogy
๐Ÿš—
Car (Blueprint)
= Class
โ†’
๐ŸŽ๏ธ
Your Car
= Object

A class is the blueprint. An object is the actual instance built from that blueprint.

04

Defining a Class

A class is a user-defined data type that bundles data members (attributes) and member functions (methods) together.

Syntax
class ClassName {
  access_specifier:
    // data members
    // member functions
};
  • Defined using the class keyword
  • Ends with a semicolon ;
  • Members are private by default
student.cpp
// Defining a Class
class Student {
  public:
    // Data Members
    string name;
    int    rollNo;
    float  cgpa;

    // Member Function
    void displayInfo() {
      cout << "Name: " << name;
      cout << "Roll: " << rollNo;
    }
};
05

Creating Objects

An object is an instance of a class. When a class is defined, no memory is allocated โ€” memory is allocated only when an object is created.

Stack Object
Student s1;

Created on the stack. Automatically destroyed when out of scope.

Heap Object
Student *s2 = new Student();

Created on the heap. Must be manually deleted.

main.cpp
#include <iostream>
using namespace std;

class Student {
  public:
    string name;
    int    rollNo;
};

int main() {
  // Creating objects
  Student s1;       // stack
  Student s2, s3;   // multiple

  // Accessing members
  s1.name   = "Alice";
  s1.rollNo = 101;

  cout << s1.name;  // Alice
  return 0;
}
06

Access Specifiers

Access specifiers control the visibility of class members. C++ provides three access specifiers:

public
Accessible from anywhere โ€” inside the class, outside the class, and in derived classes.
Use for: interface methods, getters/setters
private
Accessible only within the class. Default for class members. Hides implementation details.
Use for: data members, internal logic
protected
Accessible within the class and its derived classes. Used in inheritance.
Use for: inherited attributes
access.cpp
class BankAccount {
  private:
    double balance;       // hidden from outside
  public:
    void deposit(double amt) { balance += amt; }
    double getBalance()    { return balance; }
};
07

Constructors

A constructor is a special member function that is automatically called when an object is created. It initializes the object.

Default Constructor No parameters. Called automatically.
Parameterized Constructor Accepts arguments to initialize members.
Copy Constructor Creates a copy of an existing object.
โšก Same name as class ยท No return type ยท Called automatically
constructor.cpp
class Rectangle {
  private:
    int width, height;
  public:
    // Default Constructor
    Rectangle() {
      width = 0; height = 0;
    }
    // Parameterized Constructor
    Rectangle(int w, int h) {
      width = w; height = h;
    }
    // Copy Constructor
    Rectangle(const Rectangle &r) {
      width = r.width;
      height = r.height;
    }
    int area() { return width * height; }
};

int main() {
  Rectangle r1;           // default
  Rectangle r2(5, 10);   // param
  Rectangle r3(r2);       // copy
}
08

Destructor

A destructor is a special member function called automatically when an object goes out of scope or is deleted. It cleans up resources.

~
Prefixed with tilde ~ClassName()
0
No parameters, no return type
1
Only one destructor per class
๐Ÿ—‘
Frees dynamically allocated memory
Object Created
โ†’
Constructor Called
โ†’
Used
โ†’
Destructor Called
destructor.cpp
class FileHandler {
  private:
    int* data;
  public:
    // Constructor
    FileHandler() {
      data = new int[100];
      cout << "File Opened\n";
    }

    // Destructor
    ~FileHandler() {
      delete[] data;  // free memory
      cout << "File Closed\n";
    }
};

int main() {
  FileHandler fh; // constructor
  // ... use fh ...
} // destructor auto-called
09

Member Functions & this Pointer

Member functions define the behavior of a class. The this pointer is an implicit pointer that points to the current object.

this โ†’ current object
โ†’ this->name = object's name
โ†’ this->age = object's age
โ†’ Resolves name conflicts
Defining Outside Class
ReturnType ClassName::functionName() { }

Use :: (scope resolution operator)

this_pointer.cpp
class Person {
  private:
    string name;
    int    age;
  public:
    // 'this' resolves name conflict
    void setData(string name, int age) {
      this->name = name;
      this->age  = age;
    }

    // Defined outside class
    void display();
};

// Scope resolution operator ::
void Person::display() {
  cout << "Name: " << this->name
       << ", Age: " << this->age;
}
10

Static Members

Static members belong to the class itself, not to any individual object. They are shared across all instances.

obj1
count = ?
obj2
count = ?
obj3
count = ?
static int count = 3 Shared by ALL objects
  • Declared with static keyword
  • Defined outside the class
  • Accessed as ClassName::member
  • Static functions can only access static data
static.cpp
class Counter {
  private:
    static int count; // shared
  public:
    Counter()  { count++; }
    ~Counter() { count--; }

    static int getCount() {
      return count;
    }
};

// Define outside class
int Counter::count = 0;

int main() {
  Counter c1, c2, c3;
  cout << Counter::getCount();
  // Output: 3
}
11

Complete Example โ€” Bank Account

bank_account.cpp โ€” Putting it all together
#include <iostream>
using namespace std;

class BankAccount {
  private:                    // encapsulated
    string owner;
    double balance;
    static int totalAccounts;

  public:
    // Parameterized Constructor
    BankAccount(string name, double bal) {
      owner   = name;
      balance = bal;
      totalAccounts++;
    }

    // Destructor
    ~BankAccount() { totalAccounts--; }

    // Member Functions
    void deposit(double amt) {
      if (amt > 0) balance += amt;
    }
    void withdraw(double amt) {
      if (amt <= balance)
        balance -= amt;
      else
        cout << "Insufficient funds!\n";
    }

    void display() {
      cout << "Owner: "   << owner   << "\n"
           << "Balance: " << balance << "\n";
    }

    static int getTotal() {
      return totalAccounts;
    }
};

int BankAccount::totalAccounts = 0;

int main() {
  BankAccount acc1("Alice", 5000);
  BankAccount acc2("Bob",   3000);
  acc1.deposit(1000);
  acc2.withdraw(500);
  acc1.display();
  cout << BankAccount::getTotal(); // 2
}
12

Summary & Key Takeaways

๐Ÿ“ฆ
Class
Blueprint / template that defines data members and member functions
๐Ÿ”ต
Object
Instance of a class. Memory allocated when object is created
๐Ÿ”’
Access Specifiers
public ยท private ยท protected control member visibility
โš™๏ธ
Constructor
Auto-called on object creation. Initializes data members
๐Ÿ—‘๏ธ
Destructor
Auto-called on object destruction. Frees resources
๐Ÿ“Œ
this Pointer
Implicit pointer to the current object inside member functions
๐Ÿš€ Coming Up Next
Inheritance Polymorphism Operator Overloading Templates STL
return 0; // End of Lecture