Inheritance allows a class (called the derived class) to inherit properties and behaviors (data members and member functions) from another class (called the base class).
class DerivedClass : access_specifier BaseClass { // body of derived class };
access_specifier can be public
, private
, or protected
, affecting the visibility of base members in derived class.
#include <iostream> using namespace std; class Animal { public: void eat() { cout << "Eating..." << endl; } }; class Dog : public Animal { public: void bark() { cout << "Barking..." << endl; } }; int main() { Dog myDog; myDog.eat(); // Inherited from Animal myDog.bark(); // Defined in Dog return 0; }
Dog
inherits the eat()
method from Animal
.Dog
has its own method bark()
.myDog
can call both eat()
and bark()
.When inheriting, the base class members' accessibility can change depending on the access specifier:
public
inheritance most often for βis-aβ relationships.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!