In this article, we will explain the difference between the following code snippets:
1 | class derived : public base |
1 | class derived : base |
When defining a derived class in C++ that inherits from a base class, you have two different syntaxes to choose from: class derived : public base
and class derived : base
. These syntaxes determine the type of inheritance and have a significant impact on the accessibility of the base class members in the derived class.
It is customary to see the public
specifier used while inheriting a base class.
Public Inheritance: class derived : public base
The syntax class derived : public base
represents public inheritance. With public inheritance, the public members of the base class base
retain their access levels in the derived class derived
. Public members remain accessible as public members, protected members remain accessible as protected members, and private members remain inaccessible. This preserves the original access levels of the base class members.
Private Inheritance: class derived : base
The syntax class derived : base
represents private inheritance by default. In private inheritance, both public and protected members of the base class base
become private members in the derived class derived
. Consequently, they are not directly accessible outside the class. Private members of the base class remain inaccessible as well.
In most scenarios, it is preferred to use the explicit public
keyword (class derived : public base
) to specify public inheritance. This ensures that the access levels of the base class members are preserved in the derived class, making the code more readable and intuitive.
By understanding the difference between these two inheritance types, you can make informed decisions when designing your class hierarchy in C++.