🧩 C++ programming tutorial for beginners · Class 11 · Lesson 2 of 18 · Free
Classes and Objects in C++ – Bundle Data and Functions Together
⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in
In this lesson you will
- Define a class with data members and member functions, and create objects from it
- Protect data with private and allow safe changes through public functions
- Write a constructor and work with an array of objects
A school library tracks hundreds of books. Each book has a title, an author and a number of copies left. Keeping these in separate variables gets messy fast. A class lets you make one neat "Book" type that keeps the data and the actions together.
What is a class and an object in C++?
A class is a blueprint. It describes what every thing of one kind has. An object is one real thing made from that blueprint.
Here Student is the class. riya and aman are two objects. Each object has its own name and its own marks. Changing one does not change the other.
You reach a member with a dot: riya.marks. Don't forget the semicolon after the class's closing brace.
Try it: make a third object, kabir, give him marks and print them.
Riya scored 91 Aman scored 74
💡 public: means code outside the class may read and change these members. The next sections show why you often don't want that.
How do member functions work in a C++ class?
A class can also hold functions. They are called member functions (or methods). They work on the object's own data, so you don't pass the data in.
Inside a member function, marks means "the marks of the object this was called on". So riya.show() prints Riya's data and aman.show() prints Aman's.
A member function marked const promises not to change the object. Mark every function that only reads data as const. It is a good habit.
Try it: add a function bool passed() const that returns marks >= 33, and print it for both students.
Riya: 91 (A) Aman: 58 (C)
💡 Student riya{"Riya", 91}; fills the members in order. This shortcut works only while all members are public and there is no constructor.
What is the difference between private and public in C++?
If balance is public, any code can write fees.balance = -5000. Nothing stops the mistake. Encapsulation means hiding data and allowing changes only through checked functions.
Members under private: can be used only inside the class's own functions. Members under public: can be used from anywhere.
Here pay() refuses amounts that are zero or negative. The only way to change due is through pay(), so due can never go wrong by accident.
Try it: in main, write fees.due = 0; and run. The compiler stops you, because due is private.
Paid Rs 5000, still due Rs 7000 Rejected: Rs -200 Rejected: Rs 9000 Paid Rs 7000, still due Rs 0 Final due: Rs 0
What is a constructor in C++?
A constructor is a special member function that runs by itself when an object is created. It has the same name as the class and no return type.
Use it to give every object correct starting values. Then nobody can forget to set the title or the copies.
The part after the colon, : title(t), author(a), copies(c), is a member initializer list. It sets each member before the body runs. Lesson 7 covers constructors and destructors in depth.
Try it: create a third book with 0 copies and call issue() on it.
Added: Malgudi Days Added: Wings of Fire Issued Malgudi Days, 1 left Issued Wings of Fire, 0 left Sorry, no copies of Wings of Fire left
How do I make an array of objects in C++?
Objects are values, just like ints. You can keep many of them in an array and loop over them.
This kirana shop keeps 4 items. The loop finds the item with the lowest stock, so the shopkeeper knows what to reorder.
Try it: add a fifth item with stock 2 (change the 4s to 5) and run again.
Stock value: Rs 4487 Reorder first: Sugar (kg)
🤔 Predict the output
Think like C++: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
#include <iostream>
using namespace std;
class Student {
public:
int marks;
};
int main() {
Student a;
a.marks = 50;
Student b = a;
b.marks = 80;
cout << a.marks << " " << b.marks << "\n";
return 0;
}
Question 2. What does this print?
#include <iostream>
using namespace std;
class Wallet {
private:
int money = 100;
public:
void spend(int x) {
if (x <= money) money -= x;
}
int left() const { return money; }
};
int main() {
Wallet w;
w.spend(30);
w.spend(90);
w.spend(50);
cout << w.left() << "\n";
return 0;
}
Question 3. What does this print?
#include <iostream>
using namespace std;
class Student {
public:
int marks;
};
void addBonus(Student s) {
s.marks += 10;
}
int main() {
Student a;
a.marks = 60;
addBonus(a);
cout << a.marks << "\n";
return 0;
}
🧩 Your challenge
Write a class Ticket for a railway booking counter. It keeps the train name (string) and the seats left (int, private). The constructor takes both. book(int n) books n seats only if enough are left and prints the result; seatsLeft() returns the seats. For a train with 5 seats, booking 2, then 4, then 3 should print: Booked 2 on Rajdhani Express, 3 left Not enough seats for 4 (only 3 left) Booked 3 on Rajdhani Express, 0 left Seats left: 0
Booked 2 on Rajdhani Express, 3 left Not enough seats for 4 (only 3 left) Booked 3 on Rajdhani Express, 0 left Seats left: 0
⚠️ Common mistakes (and how to fix them)
❌ Wrong
#include <iostream>
using namespace std;
class Account {
private:
int balance = 500;
};
int main() {
Account a;
a.balance = 1000000;
cout << "Done\n";
return 0;
}
Line 11: error: 'balance' is a private member of 'Account'
✅ Right
#include <iostream>
using namespace std;
class Account {
private:
int balance = 500;
public:
void deposit(int amount) {
if (amount > 0) balance += amount;
}
int getBalance() const { return balance; }
};
int main() {
Account a;
a.deposit(1000);
cout << a.getBalance() << "\n";
return 0;
}
Private members cannot be touched from outside the class. Add a public function that changes them safely.
❌ Wrong
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
}
int main() {
Point p{2, 3};
cout << p.x + p.y << "\n";
return 0;
}
Line 7: error: expected ';' after class
✅ Right
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
};
int main() {
Point p{2, 3};
cout << p.x + p.y << "\n";
return 0;
}
A class definition must end with }; — the semicolon after the closing brace is easy to forget.
❌ Wrong
#include <iostream>
using namespace std;
class Circle {
public:
double r = 7;
double area() const { return 3.14159 * r * r; }
};
int main() {
Circle c;
cout << c.area << "\n";
return 0;
}
Line 12: error: reference to non-static member function must be called; did you mean to call it with no arguments?
✅ Right
#include <iostream>
using namespace std;
class Circle {
public:
double r = 7;
double area() const { return 3.14159 * r * r; }
};
int main() {
Circle c;
cout << c.area() << "\n";
return 0;
}
area is a function, so you must call it with brackets: c.area(). Without them you only name the function.
📌 Remember
- A class is a blueprint; each object made from it has its own copy of the data.
- Member functions work on the object's own data; mark read-only ones const.
- private hides data; public functions let outside code change it safely.
- A constructor runs when an object is created and sets good starting values.
- Objects are copied when assigned or passed by value, just like ints.
Finished the quiz and the challenge?
Questions students ask
What is the difference between a class and a struct in C++?
They are almost the same. The only difference is the default: members of a struct are public unless you say otherwise, and members of a class are private. Many people use struct for plain data and class when there are rules to protect.
What is encapsulation in C++?
Encapsulation means keeping data and the functions that work on it together, and hiding the data behind private. Outside code then changes the data only through checked public functions, so the object stays valid.
What is the this pointer in C++?
Inside a member function, this points to the object the function was called on. this->marks is the same as marks. It is useful when a parameter has the same name as a member, like this->name = name;.
Is object-oriented programming in C++ the same as in Python or Java?
The ideas are the same: classes, objects, methods and inheritance. C++ adds more control, such as private by default, const functions and choosing between copies and references.