C++ adds object-oriented programming (OOP) on top of C, and classes and objects are where OOP starts. A class lets you create your own type that holds both data and the functions that work on that data. An object is a variable of that type.
This page builds a few simple classes step by step and shows the output of each program. It assumes you know basic C++ syntax such as cout, which is covered in the C++ tutorial for beginners.
Class and object: the idea
A class is a blueprint. An object is a real thing made from it.
| Class (blueprint) | Data it describes | Things it can do | Objects |
|---|---|---|---|
Rectangle |
length, width | find area, find perimeter | a 5 x 3 rectangle, a 4 x 4 square |
Student |
roll, name, marks | show details, update marks | Anjali, Kiran |
BankAccount |
owner, balance | deposit, withdraw | Meena's account |
In C, a structure can only hold data, and you write separate functions to work on it. A C++ class keeps the data and its functions together in one unit. This idea is called encapsulation.
Your first class in C++
#include <iostream>
using namespace std;
class Rectangle {
public:
int length;
int width;
int area() {
return length * width;
}
int perimeter() {
return 2 * (length + width);
}
};
int main() {
Rectangle r1;
r1.length = 5;
r1.width = 3;
Rectangle r2;
r2.length = 4;
r2.width = 4;
cout << "r1 area: " << r1.area() << ", perimeter: " << r1.perimeter() << "\n";
cout << "r2 area: " << r2.area() << ", perimeter: " << r2.perimeter() << "\n";
return 0;
}
Output:
r1 area: 15, perimeter: 16
r2 area: 16, perimeter: 16
| Part | Meaning |
|---|---|
class Rectangle { ... }; |
Defines a new type called Rectangle. Note the ; at the end |
public: |
The members below can be used from outside the class, for example in main |
int length; int width; |
Data members: the data each object holds |
int area() |
A member function: code that works on the object's data |
Rectangle r1; |
Creates an object called r1 |
r1.length = 5; |
The dot operator reaches a member of an object |
Inside area(), length and width mean "this object's length and width". When you call r1.area(), it uses r1's values. When you call r2.area(), it uses r2's values.
Each object has its own data
#include <iostream>
#include <string>
using namespace std;
class Counter {
public:
string label;
int count = 0;
void click() {
count++;
}
};
int main() {
Counter a, b;
a.label = "Likes";
b.label = "Shares";
a.click();
a.click();
a.click();
b.click();
cout << a.label << ": " << a.count << "\n";
cout << b.label << ": " << b.count << "\n";
return 0;
}
Output:
Likes: 3
Shares: 1
a and b are two objects of the same class, but each has its own count. Clicking a does not change b. The = 0 after int count gives every new object a starting value. This style needs C++11 or later, which every current compiler supports.
Access specifiers: public and private
So far every member was public, so any code could change it. That is risky. Nothing stops r1.length = -5;.
| Access specifier | Who can use the member |
|---|---|
public |
Any code |
private |
Only member functions of the same class |
protected |
The class and classes that inherit from it |
The usual pattern is: data private, functions public. Outside code changes data only through functions that check the values first.
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int marks;
public:
void setData(string n, int m) {
name = n;
if (m >= 0 && m <= 100) {
marks = m;
} else {
marks = 0;
cout << "Invalid marks for " << n << ", set to 0\n";
}
}
int getMarks() {
return marks;
}
void show() {
cout << name << " scored " << marks << "\n";
}
};
int main() {
Student s1, s2;
s1.setData("Anjali", 88);
s2.setData("Kiran", 140);
s1.show();
s2.show();
cout << "Total: " << s1.getMarks() + s2.getMarks() << "\n";
return 0;
}
Output:
Invalid marks for Kiran, set to 0
Anjali scored 88
Kiran scored 0
Total: 88
If you try s1.marks = 50; in main, the compiler stops with an error saying that marks is private. That is the point. setData is the only way in, and it rejects marks above 100. Functions like getMarks that only return a value are often called getters, and functions that set a value are called setters.
Defining member functions outside the class
For longer functions, declare them inside the class and write the body outside using the scope resolution operator ::.
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
void setRadius(double r);
double area();
};
void Circle::setRadius(double r) {
radius = r;
}
double Circle::area() {
return 3.14 * radius * radius;
}
int main() {
Circle c;
c.setRadius(10);
cout << "Area: " << c.area() << "\n";
return 0;
}
Output:
Area: 314
Circle::area means "the area function that belongs to Circle". Without Circle::, the compiler would treat it as an ordinary function that cannot see radius.
cout prints the double value 314.0 as 314 because it drops trailing zeros by default. Large projects put the class definition in a header file (circle.h) and the function bodies in a source file (circle.cpp), which is why this style is common.
Array of objects
#include <iostream>
#include <string>
using namespace std;
class Product {
public:
string name;
int price;
int qty;
int total() {
return price * qty;
}
};
int main() {
Product cart[3] = {
{"Notebook", 45, 4},
{"Pen", 10, 5},
{"Bag", 650, 1}
};
int bill = 0;
for (int i = 0; i < 3; i++) {
cout << cart[i].name << ": " << cart[i].total() << "\n";
bill += cart[i].total();
}
cout << "Bill: " << bill << "\n";
return 0;
}
Output:
Notebook: 180
Pen: 50
Bag: 650
Bill: 880
cart[i] is one object, and cart[i].total() calls that object's function. The brace lists like {"Notebook", 45, 4} work here because every data member is public and the class has no constructor. With private data, you use a constructor instead, which is the topic of constructors and destructors in C++.
The this pointer
Inside a member function, this is a pointer to the object that called the function. You need it when a parameter has the same name as a data member.
class Box {
private:
int size;
public:
void setSize(int size) {
this->size = size; // left: the member, right: the parameter
}
};
Without this->, size = size; would assign the parameter to itself and leave the member unchanged.
class vs struct in C++
| Point | class |
struct |
|---|---|---|
| Default access | private |
public |
| Can have member functions | Yes | Yes |
| Can have constructors, inheritance | Yes | Yes |
| Common use | Objects with behaviour and protected data | Simple groups of public data |
In C++, the default access is the only real difference. A C struct, by contrast, cannot have member functions at all. See C vs C++ for the other differences between the two languages.
Common mistakes with classes
| Mistake | What happens | Fix |
|---|---|---|
Missing ; after the class |
Confusing errors on the next line | End with }; |
Using a private member in main |
Compile error: member is private | Add a public function, or rethink the design |
Forgetting ClassName:: outside the class |
Function cannot see the data members | Write void Circle::setRadius(double r) |
| Calling a function without the object | area(); in main gives an error |
Call it on an object: r1.area() |
| Leaving data members without a value | They hold garbage values | Give default values or use a constructor |
| Making everything public | Any code can set wrong values | Keep data private and check values in setters |
Quick revision
- A class is a blueprint. An object is a variable made from it.
- A class holds data members and member functions.
- Use the dot operator to reach members:
r1.area(). - Class members are private by default. Struct members are public.
- Keep data private and give public functions to read and change it.
- Define functions outside the class with
ClassName::function.
The next step is to set up an object correctly the moment it is created. That is the job of a constructor. Read C++ constructors and destructors, then practise with the OOPs interview questions and the C++ interview questions for freshers.
Frequently Asked Questions
What is a class and object in C++ in simple words?
Does a class take memory in C++?
What is the default access specifier in a C++ class?
What is a member function?
What is the scope resolution operator in C++?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Discover CodeBegun's Java Full Stack track

