Object-Oriented Programming in C++ – Classes, Inheritance, Polymorphism Explained
Object-Oriented Programming in C++ – Classes, Inheritance, Polymorphism Explained
Object-Oriented Programming (OOP) is the heart of C++. It allows programmers to model real-world problems using classes and objects. Understanding OOP is very important for software development and technical interviews.
What is Object-Oriented Programming?
OOP is a programming paradigm that organizes code into reusable objects. Each object represents a real-world entity and contains data (variables) and behavior (functions).
1. Classes and Objects in C++
A class is a blueprint, and an object is its instance.
class Car {
public:
string brand;
int speed;
void show() {
cout << brand << " " << speed;
}
};
int main() {
Car c1;
c1.brand = "BMW";
c1.speed = 200;
c1.show();
}
2. Encapsulation
Encapsulation means wrapping data and methods together and protecting them using access specifiers.
class Student {
private:
int marks;
public:
void setMarks(int m) {
marks = m;
}
int getMarks() {
return marks;
}
};
3. Inheritance
Inheritance allows one class to acquire properties of another class.
class Animal {
public:
void sound() {
cout << "Animal makes sound";
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog barks";
}
};
4. Polymorphism
Polymorphism means one function behaving differently in different situations.
class Shape {
public:
virtual void draw() {
cout << "Drawing Shape";
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing Circle";
}
};
5. Abstraction
Abstraction hides implementation details and shows only essential features.
class Vehicle {
public:
virtual void start() = 0; // Pure virtual function
};
6. Constructor and Destructor
Constructors initialize objects and destructors free resources.
class Test {
public:
Test() {
cout << "Constructor called";
}
~Test() {
cout << "Destructor called";
}
};
Common OOP Interview Questions
- Difference between class and object
- What is virtual function?
- What is runtime polymorphism?
- Explain abstract class and interface
Conclusion
OOP in C++ makes programs modular, reusable, and easier to maintain. Mastering classes, inheritance, and polymorphism will help you write professional-level software and crack interviews.
Next Post: STL in C++ Explained – Vector, Map, Set, and Algorithms
Comments
Post a Comment