Lecture No 3 Inheritence
Lecture No 3 Inheritence
Inheritance allows a class to inherit the properties and behavior from another class
The class that inherits from another class is called derived or child class.
The class being inherited from is called parent and base class.
where,
derived_class_name: name of the new class, which will inherit the base class
access-specifier: Specifies the access mode which can be either of private, public or protected. If
neither is specified, private is taken as default.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full
parent object, which contains any private members which that class
Example 2: Access the Inherited Members of the Base Class in Derived Class
C++
#include <iostream>
// Base class
class Base {
public:
// data member
int publicVar;
// member method
void display()
};
// Derived class
public:
void displayMember()
display();
publicVar = pub;
};
int main()
{
Derived obj;
obj.modifyMember(10);
obj.displayMember();
return 0;
Output
Value of publicVar: 10
In the above example, we have accessed the public members of the base class in the derived class but
we cannot access all the base class members directly in the derived class. It depends on the mode of
inheritance and the access specifier in the base class.
Types of inheritance
1. Single inheritance
2. Multi-level inheritance
3. Hybrid inheritance
4. Hierarchal inheritance
Multiple Inheritance
In multiple inheritance, a class can inherit from more than one base class. This allows the derived class to
combine functionalities from different base classes, making it more versatile. However, it can also lead to
complexities like the diamond problem (discussed below).
In C++ programming, a class can be derived from more than one parent.
For example, A class Bat is derived from base classes Mammal and Winged Animal. It makes sense
class Father {
public:
void height() {
};
class Mother {
public:
void eyes() {
};
};
int main() {
Child child;
child.height();
child.eyes();
return 0;
Output
Tall height from Father
Here, the Child class inherits from both father and Mother, gaining their characteristics (methods).
In multiple inheritance, if two base classes have a common ancestor, this can lead to ambiguity known as
the diamond problem. When the derived class tries to access a member of the common base class, it
might not know which version of the base class to use.