1. Inheritance
Inheritance is based on the concept of code reusability. It saves time of program development.
The mechanism of deriving a new derived class (subclass) from an old base class is known as
inheritance.
Types of Inheritance:
2. Defining Derived Classes
■ A derived class can be defined by specifying its relationship with the base class in
addition to its own details.
class derived_class : visibility_mode base_class
{ …………
…………//members of derived class
};
■ Default visibility mode is private
■ Example 1 (Private Derivation):
class ABC : private XYZ
{
members of ABC
};
■ Example 2 (Public Derivation):
class ABC : public XYZ
{
members of ABC
};
■ Example 3 (Default private Derivation):
class ABC : XYZ
{
Page | 1
, members of ABC
};
■ When a base class is privately inherited by a derived class
– Public members of base class become private members of derived class.
– Public members of the base class can only be accessed by member functions of
derived class
■ When a base class is publicly inherited by a derived class
– Public members of base class become public members of derived class.
– They are accessible to the objects of the derived class
3. Single Inheritance
In single inheritance a single sub class is derived from the base class.
Syntax 1:
class A //Base Class
{
……………
A
};
class B: public A //Derived Class
{
………….. B
};
Syntax 2:
class A //Base Class
{
……………
};
class B: private A //Derived Class
{
…………..
};
Example of Single Inheritance:
class base
{ public: int x;
void getdata()
{ cout << "Enter the value of x = ";
cin >> x; }
};
class derive : public base
{
private: int y;
public: void readdata()
{ cout << "Enter the value of y = ";
cin >> y; }
void product()
{ cout << "Product = " << x * y;
} };
void main()
{ derive a;
a.getdata(); a.readdata();
a.product();
}
Page | 2