In my previous blog, we discussed about the concept of classes. We’ll be taking up inheritance in this section. As usual, this will be done in an easy to understand manner ☺️ .
What comes to your mind when you think of family inheritance? Children acquiring what belongs to parents, materialistically. And if you think genetically, kids naturally inheriting the features and qualities of parents. Simple, isn’t it ☺️ .
Classes are no different. Parents represent Base Class. Kids are Derived Class. Kids inherit the features of the parent.
For the parent/kid example, lets define the classes as
protected: // protected members are //accessible by derived class
//setting parent name as GOD 🙂
strcpy (parentName, “GOD”);
}; //Parent class definition over
class kidDerived:public parentBase
void setAge(int kidAge)
age = kidAge;
cout<<“parent name is: “<<parentName<<endl;
cout <<” kid’s age is : ” <<age<<endl;
}; //derived class definition over
And now, lets define the the main() function
In the above example, we create an object of derived class, kidDerived .
Derived class has access to protected members of the base class. The functions of derived class therefore can modify the protected variables of the base class, namely age and parentName .
Public members can be accessed by objects, therefore functions showParentName(), setAge(), and showAge() are accessible by object objKid.
4. Access Specifiers
Access specifiers define the scope of access and visibility of members of base class.
- Public: public members of a class are accessible by all. Derived classes, and objects of derived classes can access the public members of base class.
- Protected: protected members of base class can be accessed by it’s derived class only. Objects of derived class cannot access protected members of base class.
- Private: private members are inaccessible to all i.e. derived class and objects of derived class cannot access private members of base class.
Friends, I hope I was successful in raising the curtain from inheritance. I am sure you feel complacent with it now 😀 . In our next blog, we’ll be taking up another example of inheritance, to derive classes for various types of social media ☺️ .