In C++, it is possible to inherit attributes and methods from one class to another. This is one of the most powerful features of Object-Oriented Programming because it promotes code reusability.
We group the "inheritance concept" into two categories:
To inherit from a class, use the colon symbol : followed by an access specifier (public is most common) and the name of the base class.
Let's look at an example where a Car class inherits from a Vehicle base class.
#include <iostream> #include <string> using namespace std;// Base class (Parent) class Vehicle { public: string brand = "Ford"; void honk() { cout << "Tuut, tuut! \n"; } };
// Derived class (Child) inherits from Vehicle class Car : public Vehicle { public: string model = "Mustang"; };
int main() { Car myCar;
// Call the inherited method from the Vehicle class myCar.honk();
// Access inherited attribute from Vehicle and attribute from Car cout << myCar.brand + " " + myCar.model << "\n"; return 0; }
It is incredibly useful for code reusability. You can reuse fields and methods of an existing class when you create a new class. If you have Dog, Cat, and Cow classes, they can all inherit an eat() method from an Animal base class, saving you from writing the same code three times!
protected Access SpecifierWe discussed public and private earlier. Now we can finally use the third access specifier: protected.
A protected member is similar to a private member—it cannot be accessed outside the class. However, unlike private members, protected members can be accessed by derived classes (child classes).
#include <iostream> using namespace std;class Employee { protected: // Protected access specifier int salary; };
// Programmer inherits from Employee class Programmer : public Employee { public: int bonus; void setSalary(int s) { salary = s; // Can access protected member of parent! } int getSalary() { return salary; } };
int main() { Programmer myObj; myObj.setSalary(50000); myObj.bonus = 15000; cout << "Salary: " << myObj.getSalary() << "\n"; cout << "Bonus: " << myObj.bonus << "\n"; return 0; }
Which symbol is used to inherit a class in C++?