You are on page 1of 9

Inheritance

Modes of Inheritance, Types of Inheritance


Inheritance
• Inheritance(the mechanism by
Vehicle
which one class acquires the
properties of another class)
• New classes created from existing Wheeled
Boat
classes Vehicle

• Absorb attributes and behaviors.


• Concepts at lower levels are Bicycle Car
more specific (inherit properties
of concepts at higher levels)
2-Door 4-Door
Inheritance Continues…
• The language mechanism by which one class acquires the properties
(data and operations) of another class there are two types of classes
• Base Class (or superclass)
• The class being inherited from
• Derived Class (or subclass)
• The class that inherits
Advantages of inheritance
When a class inherits from another class, there are three
benefits:
1. You can reuse the methods and data of the existing class
2. You can extend the existing class by adding new data and new
methods
3. You can modify the existing class by overloading its methods with
your own implementations
Define a Class Hierarchy

• Syntax:
class DerivedClassName : access-level BaseClassName
where
• access-level specifies the type of derivation
• private by default, or
• public
• protected
• Any class can serve as a base class
• Thus a derived class can also be a base class
5
Access Rights of Derived Classes
• Modes of Inheritance:
• The mode of inheritance defines the access level for the members of derived
class that are inherited from the base class

Modes of Inheritance
private protected public
for Members
Access Control

private - - -
protected private protected protected
public private protected public
Constructor Rules for Derived Classes
The default constructor and the destructor of the base class are always called
when a new object of a derived class is created or destroyed.

class A { class B : public A


public: {
A() public:
{cout<< “A:default”<<endl;} B (int a)
A (int a) {cout<<“B”<<endl;}
{cout<<“A:parameter”<<endl;} };
};

output: A:default
B test(1); 7
B
Types of Inheritance
• Single Inheritance:
• A class inheriting from only one class
is called Single Inheritance

• Multiple Inheritance:
• A class can inherit from more than
one classes is called multiple
Inheritance
Types of Inheritance Continues…
• Multi-level Inheritance:
• A class is inherited from another
already derived(inherited) class

• Hybrid Inheritance:
• Combining more than one type of
inheritance is called Hybrid
Inheritance

You might also like