public (preserves accessibility), protected (accessible within class and derived classes, not outside), private (accessible only within the defining class)class Animal { public: void eat() { cout << "eats\n"; } };
class Dog : public Animal { public: void bark() { cout << "barks\n"; } };
// Dog inherits eat() from Animal, adds bark() of its own
MCQ Trap: C++ supports multiple inheritance; many other OOP languages (e.g., Java) restrict classes to single inheritance and use interfaces instead.
A derived class gets access to all public and protected members of its base class (not private — those stay locked to the base class itself, even for derived classes). It can then add new members and override existing behavior.
class Animal
{
protected:
string name;
public:
Animal(string n) : name(n) {}
void eat() { cout << name << " eats\n"; }
};
class Dog : public Animal
{
public:
Dog(string n) : Animal(n) {} // must call base constructor explicitly
void bark() { cout << name << " barks\n"; } // name accessible -- it's protected, not private
};
int main()
{
Dog d("Rex");
d.eat(); // inherited from Animal
d.bark(); // Dog's own method
return 0;
}
When a Dog object is created, Animal's constructor runs before Dog's own constructor body executes. Destructors run in the opposite order (derived first, then base) — a common exam trap.
class A { public: A() { cout << "A constructed\n"; } ~A() { cout << "A destroyed\n"; } };
class B : public A { public: B() { cout << "B constructed\n"; } ~B() { cout << "B destroyed\n"; } };
// B b; --> Output: "A constructed", "B constructed", then on scope exit: "B destroyed", "A destroyed"
| Base member | public inheritance |
protected inheritance |
private inheritance |
|---|---|---|---|
public |
stays public |
becomes protected |
becomes private |
protected |
stays protected |
stays protected |
becomes private |
private |
not accessible at all | not accessible at all | not accessible at all |
public inheritance (class Dog : public Animal) is by far the most common — it preserves the "is-a" relationship cleanly.