Introduction & Syntax
OOPS Concepts · Study material
OOPS concepts in C++ – object-oriented programming – organise a program around objects that bundle data with the functions that work on it. C++ supports OOP through classes and builds on four pillars: encapsulation, abstraction, inheritance and polymorphism. Together with constructors and destructors, access specifiers, this, static members and virtual functions, they let you model real-world things – accounts, students, shapes, payments – in code that is easier to understand, extend and test. "Explain the four pillars of OOP with examples" is probably the most frequently asked C++ interview question. This page explains every concept with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Procedural vs object-oriented programming; classes and objects
- The four pillars: encapsulation, abstraction, inheritance, polymorphism
- Constructors, destructors, this and static members
- Compile-time vs run-time polymorphism, virtual functions, abstract classes
- Composition vs inheritance, object slicing and the SOLID principles
Procedural vs object-oriented programming
In procedural code (as in C), data and the functions that manipulate it are separate: any function can change any data. In object-oriented code, the data of a bank account and the operations allowed on it live together in one class, and the class decides who may change what.
| Procedural | Object-oriented | |
|---|---|---|
| Building block | functions | objects (classes) |
| Data | usually global or passed around freely | hidden inside objects |
| Reuse | calling functions | inheritance, composition, polymorphism |
| Change | a data change can affect many functions | changes stay inside one class |
| Examples | C, early BASIC | C++, Java, C#, Python |
Classes and objects
A class is a user-defined type – a blueprint describing the data members (attributes) and member functions (methods) its objects will have. An object is an instance of that class, with its own copy of the data. A struct is the same as a class except that its members are public by default.
#include <iostream>
#include <string>
class Car { // a class is a blueprint: data + behaviour
public:
std::string brand;
int speed = 0;
void accelerate(int by) { speed += by; }
void show() const { std::cout << brand << " at " << speed << " km/h\n"; }
};
int main() {
Car a; // an object is an instance of the class
a.brand = "Tata";
a.accelerate(40);
Car b{"Mahindra", 20}; // each object has its own copy of the data
b.accelerate(30);
a.show();
b.show();
return 0;
}
Tata at 40 km/h Mahindra at 50 km/h
Pillar 1 – Encapsulation
Encapsulation bundles data and methods together and hides the data behind an interface. Members marked private are accessible only inside the class; public members form its interface; protected members are also visible to derived classes. Because outside code can change the data only through member functions, the class can enforce its rules – a balance never goes negative.
#include <iostream>
#include <string>
class BankAccount {
private: // hidden: only member functions can touch it
std::string owner_;
double balance_ = 0;
public:
explicit BankAccount(std::string owner) : owner_(std::move(owner)) {}
bool deposit(double amount) {
if (amount <= 0) return false; // the class protects its own rules (invariants)
balance_ += amount;
return true;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) return false;
balance_ -= amount;
return true;
}
double balance() const { return balance_; } // read-only access
};
int main() {
BankAccount acc("Asha");
acc.deposit(5000);
std::cout << acc.withdraw(7000) << ' ' << acc.withdraw(1500) << ' ' << acc.deposit(-10) << '\n';
std::cout << acc.balance() << '\n';
// acc.balance_ = 1e9; error: balance_ is private
return 0;
}
0 1 0 3500
| Access specifier | Same class | Derived class | Outside code |
|---|---|---|---|
public | ✔ | ✔ | ✔ |
protected | ✔ | ✔ | ✘ |
private | ✔ | ✘ | ✘ |
Pillar 2 – Abstraction
Abstraction shows what an object does and hides how it does it. In C++ it is expressed with abstract classes (classes with pure virtual functions, = 0) that act as interfaces: code is written against the interface and works with any implementation. Encapsulation hides data; abstraction hides complexity and implementation choices.
#include <iostream>
#include <memory>
#include <string>
class Notifier { // abstract class: WHAT, not HOW
public:
virtual void send(const std::string& msg) = 0; // pure virtual function
virtual ~Notifier() = default;
};
class EmailNotifier : public Notifier {
public:
void send(const std::string& msg) override { std::cout << "Email: " << msg << '\n'; }
};
class SmsNotifier : public Notifier {
public:
void send(const std::string& msg) override { std::cout << "SMS: " << msg.substr(0, 10) << "...\n"; }
};
void alert(Notifier& n) { n.send("Your exam result is ready"); } // works with any notifier
int main() {
EmailNotifier e;
SmsNotifier s;
alert(e);
alert(s);
return 0;
}
Email: Your exam result is ready SMS: Your exam ...
Pillar 3 – Inheritance
Inheritance creates a new class (derived/child) from an existing one (base/parent), reusing its members and adding or changing behaviour. It models an IS-A relationship: a Student is a Person. C++ supports single, multiple, multilevel, hierarchical and hybrid inheritance, and public, protected and private inheritance modes.
#include <iostream>
#include <string>
class Person { // base class
protected:
std::string name_;
public:
explicit Person(std::string n) : name_(std::move(n)) {}
void introduce() const { std::cout << "I am " << name_ << '\n'; }
};
class Student : public Person { // Student IS-A Person
int roll_;
public:
Student(std::string n, int roll) : Person(std::move(n)), roll_(roll) {}
void study() const { std::cout << name_ << " (roll " << roll_ << ") is studying\n"; }
};
int main() {
Student s("Ravi", 12);
s.introduce(); // inherited from Person
s.study(); // added by Student
return 0;
}
I am Ravi Ravi (roll 12) is studying
Pillar 4 – Polymorphism
Polymorphism ("many forms") lets one interface behave differently for different types. C++ has two kinds:
- Run-time (dynamic) polymorphism –
virtualfunctions overridden in derived classes and called through a base pointer or reference; the call is resolved while the program runs (dynamic binding, usually via a vtable). - Compile-time (static) polymorphism – function overloading, operator overloading and templates; the compiler picks the function.
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual double area() const = 0;
virtual const char* name() const { return "shape"; }
virtual ~Shape() = default;
};
class Circle : public Shape {
double r_;
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
const char* name() const override { return "circle"; }
};
class Square : public Shape {
double s_;
public:
explicit Square(double s) : s_(s) {}
double area() const override { return s_ * s_; }
const char* name() const override { return "square"; }
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1));
shapes.push_back(std::make_unique<Square>(3));
for (const auto& s : shapes) // one call, different behaviour
std::cout << s->name() << ": " << s->area() << '\n';
return 0;
}
circle: 3.14159 square: 9
#include <iostream>
#include <string>
struct Money {
long paise;
Money operator+(const Money& o) const { return {paise + o.paise}; } // operator overloading
};
void print(int x) { std::cout << "int " << x << '\n'; } // function overloading
void print(const std::string& s) { std::cout << "text " << s << '\n'; }
void print(const Money& m) { std::cout << "Rs " << m.paise / 100 << '.' << m.paise % 100 << '\n'; }
template <typename T>
T twice(T x) { return x + x; } // templates
int main() {
print(42);
print("hello");
print(Money{1050} + Money{275});
std::cout << twice(21) << ' ' << twice(std::string("ab")) << '\n';
return 0;
}
int 42 text hello Rs 13.25 42 abab
Constructors and destructors
A constructor has the class's name and no return type; it runs automatically when an object is created and puts it into a valid state. A destructor (~ClassName) runs automatically when the object is destroyed and releases its resources. Objects are destroyed in the reverse order of their creation – the basis of RAII.
#include <iostream>
#include <string>
class Logger {
std::string tag_;
public:
explicit Logger(std::string tag) : tag_(std::move(tag)) { std::cout << "open " << tag_ << '\n'; }
~Logger() { std::cout << "close " << tag_ << '\n'; } // runs automatically
};
int main() {
Logger app("app");
{
Logger req("request");
std::cout << "handling\n";
} // req destroyed here
std::cout << "done\n";
return 0;
} // app destroyed here
open app open request handling close request done close app
this and static members
Inside a member function, this is a pointer to the object the function was called on; returning *this enables method chaining. A static data member is shared by all objects of the class (one copy in total), and a static member function belongs to the class rather than to an object, so it has no this.
#include <iostream>
class Counter {
static inline int created_ = 0; // one variable shared by all objects
int value_ = 0;
public:
Counter() { ++created_; }
Counter& add(int n) { value_ += n; return *this; } // this points to the current object
int value() const { return value_; }
static int created() { return created_; } // called on the class, no object needed
};
int main() {
Counter a, b, c;
a.add(5).add(10).add(1); // chaining works because add returns *this
std::cout << a.value() << ' ' << b.value() << ' ' << Counter::created() << '\n';
return 0;
}
16 0 3
Composition vs inheritance
Composition builds a class from other objects – a Car HAS-A Engine. It is usually more flexible than inheritance: parts can be replaced, and the outer class exposes only what it wants. The common advice is "prefer composition over inheritance"; use inheritance when the IS-A relationship is real and you need polymorphism.
#include <iostream>
#include <string>
class Engine {
public:
explicit Engine(int hp) : hp_(hp) { std::cout << "Engine " << hp_ << "hp built\n"; }
void start() const { std::cout << "engine started\n"; }
private:
int hp_;
};
class Car { // Car HAS-A Engine (composition)
std::string model_;
Engine engine_; // members are built before the constructor body runs
public:
Car(std::string m, int hp) : model_(std::move(m)), engine_(hp) { std::cout << model_ << " ready\n"; }
void drive() const { engine_.start(); std::cout << model_ << " is moving\n"; }
};
int main() {
Car c("Nexon", 120);
c.drive();
return 0;
}
Engine 120hp built Nexon ready engine started Nexon is moving
SOLID principles in one table
| Principle | Meaning |
|---|---|
| Single responsibility | a class should have one reason to change |
| Open/closed | open for extension (new derived classes), closed for modification |
| Liskov substitution | a derived object must work wherever its base is expected |
| Interface segregation | many small interfaces are better than one large one |
| Dependency inversion | depend on abstractions (interfaces), not concrete classes |
Common mistakes
- Public data members everywhere – nothing protects the class's rules.
- Missing virtual destructor in a base class used polymorphically – deleting through a base pointer is undefined behaviour.
- Object slicing – passing or storing a derived object by value as its base loses the derived part.
- Forgetting override – a typo in the signature silently creates a new function instead of overriding.
- Inheritance for code reuse only when there is no real IS-A relationship – use composition.
- Forgetting the semicolon after a class definition.
Key points to remember
- A class is a blueprint; an object is an instance with its own data.
- Encapsulation hides data; abstraction hides implementation.
- Inheritance = IS-A; composition = HAS-A.
- Virtual functions give run-time polymorphism; overloading and templates give compile-time polymorphism.
- Constructors initialize, destructors clean up – in reverse order.
- Give polymorphic base classes a virtual destructor.
Frequently asked questions
What are the four pillars of OOP?
Encapsulation (bundling and hiding data), abstraction (exposing only essential behaviour), inheritance (deriving new classes from existing ones) and polymorphism (one interface, many implementations).
Is C++ a pure object-oriented language?
No. C++ is multi-paradigm: it supports procedural, object-oriented, generic and functional styles, and has free functions and fundamental types that are not objects of classes.
What is the difference between a class and a struct in C++?
Only the defaults: class members and base classes are private by default, struct members and base classes are public. By convention, struct is used for simple data aggregates.
Where can I learn more?
Read Object-Oriented Programming in C++ and C++ Classes and Objects, then practise with the exercises below.