A class in C++ is a user-defined type that groups data members and member functions.
An object is an instance of a class. It has its own copy of non-static data members.
Classes and objects are the base of C++ object-oriented programming, but this page focuses only on class syntax, object creation, members, constructors, destructors, object lifetime, static members, and access rules.
A class is a blueprint for creating objects. It describes what data an object stores and what operations can be performed on that data.
In C++, a class can contain variables, functions, constructors, destructors, static members, constants, and access specifiers. The most common use is to keep related data and behavior together in one named type.
class Student {
private:
int rollNo;
double marks;
public:
void setData(int r, double m) {
rollNo = r;
marks = m;
}
void display() {
cout << rollNo << " " << marks << endl;
}
};
An object is a real variable created from a class. If a class is a blueprint, an object is the actual item built from that blueprint.
Each object has its own non-static data. For example, two Student objects can have different roll numbers and marks, even though they come from the same Student class.
#include <iostream>
using namespace std;
class Student {
private:
int rollNo;
double marks;
public:
void setData(int r, double m) {
rollNo = r;
marks = m;
}
void display() {
cout << "Roll No: " << rollNo << ", Marks: " << marks << endl;
}
};
int main() {
Student s1;
Student s2;
s1.setData(101, 87.5);
s2.setData(102, 91.0);
s1.display();
s2.display();
return 0;
}
The class itself is only the plan. Memory for normal data members is allocated when objects are created from that class.
| Class | Object |
|---|---|
| Blueprint or user-defined type | Instance of a class |
| Does not store actual per-object values by itself | Stores actual values in memory |
| Declared once | Can be created many times |
| Example: class Student | Example: Student s1 |
Access specifiers control where class members can be used. They help protect data and expose only the functions that outside code should use.
| Specifier | Accessible From | Common Use |
|---|---|---|
| private | Only inside the same class | Hide data members |
| public | Anywhere the object is visible | Expose methods like setData() and display() |
| protected | Same class and derived classes | Used mainly with inheritance |
Data members represent the state of an object. Member functions represent the behavior of an object. Good class design keeps data private and provides public functions to read or modify that data safely.
#include <iostream>
#include <string>
using namespace std;
class Product {
private:
string name;
double price;
public:
void setName(string n) {
name = n;
}
void setPrice(double p) {
if (p >= 0) {
price = p;
}
}
string getName() const {
return name;
}
double getPrice() const {
return price;
}
};
int main() {
Product p;
p.setName("Keyboard");
p.setPrice(1200);
cout << p.getName() << " costs " << p.getPrice() << endl;
return 0;
}
For small functions, writing the body inside the class is fine. For larger functions, declare the function inside the class and define it outside using the scope resolution operator (::).
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
void setDimensions(int l, int w);
int area() const;
};
void Rectangle::setDimensions(int l, int w) {
length = l;
width = w;
}
int Rectangle::area() const {
return length * width;
}
int main() {
Rectangle r;
r.setDimensions(10, 5);
cout << "Area = " << r.area() << endl;
return 0;
}
A constructor is a special member function that runs automatically when an object is created. It is used to initialize data members.
#include <iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point() : x(0), y(0) {}
Point(int xValue, int yValue) : x(xValue), y(yValue) {}
void print() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1;
Point p2(3, 4);
p1.print();
p2.print();
return 0;
}
A destructor is a special member function that runs automatically when an object is destroyed. It is commonly used to release resources such as dynamic memory, file handles, or network connections.
For normal stack objects, the destructor runs when the object goes out of scope. For dynamically allocated objects created with new, the destructor runs when delete is used.
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}
~Demo() {
cout << "Destructor called" << endl;
}
};
int main() {
Demo d;
cout << "Inside main" << endl;
return 0;
}
Constructor called
Inside main
Destructor called
Objects can be created in different ways depending on lifetime and memory needs.
| Creation Style | Example | Notes |
|---|---|---|
| Stack object | Student s1; | Destroyed automatically when scope ends |
| Parameterized object | Point p(3, 4); | Calls matching constructor |
| Pointer to object | Student* ptr = &s1; | Uses -> to access public members |
| Dynamic object | Student* p = new Student(); | Must be deleted manually unless using smart pointers |
#include <iostream>
using namespace std;
class Demo {
public:
void show() {
cout << "Object function called" << endl;
}
};
int main() {
Demo d;
d.show(); // dot operator
Demo* ptr = &d;
ptr->show(); // arrow operator
Demo* heapObj = new Demo();
heapObj->show();
delete heapObj;
return 0;
}
A class is a type, so you can create arrays or vectors of objects the same way you create arrays or vectors of int, double, or string values.
Arrays of objects are useful when the number of objects is fixed. Vectors are usually better when the number of objects can grow or shrink.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
private:
string name;
int marks;
public:
Student(string studentName, int studentMarks)
: name(studentName), marks(studentMarks) {}
void display() const {
cout << name << " scored " << marks << endl;
}
};
int main() {
vector<Student> students = {
Student("Asha", 88),
Student("Ravi", 92),
Student("Neha", 85)
};
for (const Student& student : students) {
student.display();
}
return 0;
}
A normal data member belongs to each object. A static data member belongs to the class itself and is shared by all objects.
#include <iostream>
using namespace std;
class Counter {
private:
static int count;
public:
Counter() {
count++;
}
static int getCount() {
return count;
}
};
int Counter::count = 0;
int main() {
Counter c1, c2, c3;
cout << "Objects created: " << Counter::getCount() << endl;
return 0;
}
When one object is initialized from another object of the same class, C++ copies the data members. For simple classes that contain int, double, string, or other safe value types, the default copy behavior is usually fine.
When a class owns raw dynamic memory or another resource, copying needs extra care. In that case, define proper copy behavior or prefer standard library types that manage memory safely.
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
public:
Book(string bookTitle) : title(bookTitle) {}
void show() const {
cout << title << endl;
}
};
int main() {
Book b1("C++ Basics");
Book b2 = b1;
b1.show();
b2.show();
return 0;
}
Inside a non-static member function, this is a pointer to the current object. It is useful when parameter names match data member names or when returning the current object.
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box& setLength(int length) {
this->length = length;
return *this;
}
void show() const {
cout << "Length = " << length << endl;
}
};
int main() {
Box b;
b.setLength(10).show();
return 0;
}
This example combines private data, constructor, setters, getters, const function, object creation, and method calls.
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string owner;
double balance;
public:
BankAccount(string ownerName, double openingBalance)
: owner(ownerName), balance(openingBalance) {}
string getOwner() const {
return owner;
}
double getBalance() const {
return balance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
void display() const {
cout << owner << " balance: " << balance << endl;
}
};
int main() {
BankAccount account("Ravi", 5000);
account.deposit(1500);
account.withdraw(700);
account.display();
return 0;
}
Ravi balance: 5800
A class is a user-defined type that groups data members and member functions into one blueprint.
An object is an instance of a class. It stores actual values and can call public member functions.
C++ makes class members private by default to support data hiding and safer object design.
Explore 500+ free tutorials across 20+ languages and frameworks.