Inheritance in C++
Inheritance is a fundamental concept in object-oriented programming, and it allows you to create new classes (derived or subclass) that inherit properties and behaviors from existing classes (base or superclass). In C++, inheritance is a key feature, and it enables you to establish a hierarchy of classes. Here's how inheritance works in C++:
Base Class (Superclass):
In this example, student is a base class that defines a common property (name and age) and a common behavior (calculating the getdata() and putdata()). The public access specifier allows derived classes to access these members.
Derived Class (Subclass):
The Employee class is a derived class that inherits from the Student
class. To specify inheritance, you use the colon (:
) followed by the base class name. The derived class has access to the Name and age members of the base class.
Using Inheritance:
In this example, a Employee object is created, and it can access both the getdata() and putdata() function (inherited from Student
) and its own get() and put() function. The derived class has both the properties and behaviors of the base class, and it can extend or override them as needed.
Example:-