In this lesson, you will learn
Inheritance is one of the fundamental concepts in object-oriented programming (OOP) and is a key feature of the C++ programming language.
It allows you to create new classes that are based on existing classes, inheriting their properties and behaviors.
Inheritance promotes code reuse and is a crucial part of building complex, hierarchical class structures.
Before diving into the details of inheritance, let’s clarify some essential terminology:
Base Class (Parent Class or Super Class): The class whose properties and behaviors are inherited by another class.
Derived Class (Child Class or Sub Class): The class that inherits properties and behaviors from a base class.
In C++, there are several types of inheritance, each serving different purposes:
A derived class inherits from a single base class.
A derived class is created from another derived class.
A derived class inherits from multiple base classes.
Multiple derived classes inherit from a single base class.
A combination of different types of inheritance.
The syntax for inheriting from a base class is as follows:
class BaseClass {
// Base class members
};
class DerivedClass : access_specifier BaseClass {
// Derived class members
};
‘access_specifier
can be either public
, protected
, or private
and determines the visibility of the base class members in the derived class.
1. Private derivation
class Derived: private Base //Private derivation
{
// Members of derived class
}
In this case, the public member of a Base class becomes the private member of the Derived class.
Therefore public members of a Base class can only be accessed by the member functions of the Derived class. They are inaccessible to the object of the Derived class.
Note: The public members of a class can be accessed by its own object using the dot operator.
2. Public Derivation
class Derived: public Base //Public derivation
{
// Members of derived class
}
In this case, the public member of a Base class becomes the public member of the Derived class and is accessible to the object of a Derived class.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.