C++ Inheritance Introduction
In this page:
What is Inheritance?
Inheritance lets a new class, called the derived class, automatically acquire the properties and methods of an existing class, called the base class. This promotes code reuse by letting related classes share common behavior instead of each reimplementing it independently.
Example: What is Inheritance?
#include <iostream>
class Animal {
public:
void eat() { std::cout << "Eating" << std::endl; }
};
class Dog : public Animal {
public:
void bark() { std::cout << "Barking" << std::endl; }
};
int main() {
Dog d;
d.eat();
d.bark();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Base and Derived Class Constructors
When you create an object of a derived class, the base class's constructor always runs first to set up the inherited portion of the object, and only after that finishes does the derived class's own constructor run to initialize the parts it added.
Example: Base and Derived Class Constructors
#include <iostream>
class Animal {
public:
Animal() { std::cout << "Animal constructed" << std::endl; }
};
class Dog : public Animal {
public:
Dog() { std::cout << "Dog constructed" << std::endl; }
};
int main() {
Dog d;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Public Inheritance Access
With public inheritance, any member that was public in the base class remains public in the derived class, meaning external code can access it through a derived object exactly as freely as it could through a base object.
Example: Public Inheritance Access
#include <iostream>
class Animal {
public:
int legs = 4;
};
class Dog : public Animal {};
int main() {
Dog d;
std::cout << d.legs << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Protected Access Specifier
Protected members can never be accessed from outside the class hierarchy entirely, but unlike private members, they remain freely accessible inside any class that derives from the one that declared them — useful for internal state a subclass legitimately needs to build on.
Example: Protected Access Specifier
#include <iostream>
class Animal {
protected:
int age = 2;
};
class Dog : public Animal {
public:
void showAge() { std::cout << age << std::endl; }
};
int main() {
Dog d;
d.showAge();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Overriding Base Class Methods
Method overriding lets a derived class supply its own specific implementation of a function that the base class already defines, replacing the inherited behavior with logic tailored to that particular subclass.
Example: Overriding Base Class Methods
#include <iostream>
class Animal {
public:
void speak() { std::cout << "..." << std::endl; }
};
class Dog : public Animal {
public:
void speak() { std::cout << "Woof" << std::endl; }
};
int main() {
Dog d;
d.speak();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: