Inheritance in C++ part 1
Inheritance:
A programming technique that is used to reuse an existing class to create a new class is called inheritance. The new class inherits all the behaviour of the original class.
The existing class that is raised to create a new class is called super class, base class or parent class. The new class that inherits the properties and functions of the existing class is known as subclass, derived class or child class.
The basic principle of inheritance is that each child class shares common properties with the class from which it is derived.The child class inherits all properties of the parent class and can add its own capabilities.
Example:
Suppose we have a class named Vehicle. The derived classes of this class may share similar properties such as wheels and motor etc.
Additionally, derived classes may have their own particular characteristics. For example, a derived class bus may have seats for people but, another derived class truck may have space to carry goods.
Advantages of inheritance:
- Reusability
- Saves time and effort
- Increase program structure and reliability
Types of inheritance:
- Single inheritance
- Multilevel inheritance
- Multiple inheritance
- Hierarchical inheritance
- Hybrid inheritance
All will be discussed in detail one by one.
Single level Inheritance:
A type of inheritance in which a child class is derived from single parent class is known as single level inheritance.
Syntax:
class A // base class
{
..........
};
class B : acess_specifier A // derived class
{
} ;
Access specifiers can be public,protected
and private
Example:
#include <iostream>
using namespace std;
class Vehicle //single parent class
{
public:
int x;
void getData()
{
cout << "Enter the value of x = "; cin >> x;
}
};
class derive : public Vehicle //single derived class
{
private:
int y;
public:
void readData()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};
int main()
{
derive a; //object of derived class
a.getData();
a.readData();
a.product();
return 0;
}
Output:
Enter the value of x = 3 Enter the value of y = 4 Product = 12
Watch a quick editorial here:
great efforts
ReplyDeleteGood
ReplyDelete