Inheritance
Class Keyword vs Struct Keyword w.r.t. Inheritance
- If No access level(Default) is specified for the inheritance, the compiler assumes “private” for classes declared with keyword “class” and “public” for those declared with “struct”.
Public Vs Private Vs Protected Inheritance:
- Actually, most use cases of inheritance in C++ should use public inheritance.
- When other access levels are needed for base classes, they can usually be better represented as member variables instead.
What is Inherited from Base Class?
- In principle, a publicly derived class inherits access to every member of a base class EXCEPT:
- Base class constructors and Base class destructor
- Base class assignment operator members (operator=)
- Base class friends
- Base class private members
- Even though access to the constructors and destructor of the base class is not inherited as such, they are automatically called by the constructors and destructor of the derived class.
-
Unless otherwise specified, the constructors of a derived class calls the default constructor of its base classes (i.e., the constructor taking no arguments).
//will call default constructor of base class `Person` automatically, assume Student is derived from Person class Student(string szName, int iYear, string szUniversity) { m_szUniversity = szUniversity; }
-
Calling a different constructor of a base class is possible, using the same syntax used to initialize member variables in the constructor-initialization list.
If you want to call the parametrized(user defined) constructor of a base class from a derived class then you need to write a parametrized constructor of a derived class as below Student(string szName, int iYear, string szUniversity) :Person(szName, iYear) { m_szUniversity = szUniversity; }
Public Inheritance:
-
Private, Protected, Public members accessibility with respect to Public Inheritance.
Protected Inheritance:
-
Private, Protected, Public members accessibility with respect to Protected Inheritance.