In this article, we will read about Inheritance in C++.
Inheritance is essential feature
of Object Oriented Programming. Important aspect of Inheritance is code
reusability. It is sometime necessary to reuse a same code rather than writing
same code over and over. It also save time, money and increase reliability. In
inheritance, a new class inherits some properties and characteristics of
already existing class.
The new class which is inheriting properties of existing class is called
as derived class or sub class or child class.
The class whose properties are inherited by derived class is called base class or super class or parent class.
The derived class can inherits some or all the properties of base class
based on the visibility mode.
Advantages of Inheritance in C++
(1) Code reusability
(2) Save time for writing same code over and over.
(3) Method overriding
(4) Usage of virtual function
(5) Extensibility
Disadvantages of Inheritance in C++
(1) Derived class depends on base class.
(2) Inherited functions work slower than normal functions.
Syntax of Inheritance in C++
class derived_class_name : visibility_mode base_class_name
Example:
class A
{
public:
int a;
};
class B: public A
{
public:
int b;
};
Inheritance Visibility Modes in C++
Visibility modes defines which
properties of base class is inherited by derived class.
Note: All members of base class can be
inherited except private members.
Public Mode
In public mode, public members of base
class becomes public members of derived class and protected members of base
class becomes protected members of derived class.
Syntax:
class derived_class_name : public
base_class_name
Example:
class A
{
public:
int a;
};
class B: public A
{
public:
int b;
};
Private Mode
In private mode, protected and public
members of base class becomes private members of derived class. So these
members cannot be accessed outside the derived class.
Syntax:
class derived_class_name : private
base_class_name
Example:
class A
{
public:
int a;
};
class B: private A
{
public:
int b;
};
Protected Mode
In protected mode, public and protected
members of base class becomes protected members of derived class.
Syntax:
class derived_class_name : protected
base_class_name
Example:
class A
{
public:
int a;
};
class B: protected A
{
public:
int b;
};
0 comments:
Post a Comment