Blog

Starting Inheritance in C++

Inheritance is the process of extending existing classes by adding new features or modifying existing features. The existing class is called the base class while the new class is called the derived class. For proper Inheritance there must be an “IS A” relationship between classes. For example every Employee IS A Person, every Sportsperson IS A Person, every Manager IS AN Employee. Thus we can extend Employee from Person, Sportsperson from Employee, Manager from Employee. We cannot extend Employee from Book because an Employee IS NOT A Book. We cannot do inheritance the reverse way either. Every Person IS NOT an Employee.

Inheritance promotes code reuse and it also provides backward compatibility.

Backward Compatibility

Imagine you are building a new software Animato-1. It is about creating fabulous animations. People create animations and save their animations.

After a few years you add some new features to Animato and release the new version. Its called Animato-2.

What should be the relationship between Animato-2 and Animato-1? All animations made on Animato-1 must open on Animato-2 and be editable, functional etc. This is being backward compatible. Inheritance( the public variety) will provide this automatically.

An Inheritance Sample.


#include <iostream>
#include<string.h>
using namespace std;
class Person
{
private: char name[50],address[50];
private: int age;

public:Person(char name[50],char address[50],int age)
{
strcpy(this->name,name);
strcpy(this->address,address);
this->age=age;
}
public:void print()
{
cout<<"\nName="<<name<<", Address ="<<address<<", Age ="<<age;
}
};
class Employee:Person
{
private: char post[50];
private: int salary;
public:Employee(char name[50],char address[50],int age,char post[50],int salary)
:Person(name,address,age)
{

strcpy(this->post,post);
this->salary=salary;
}
public: void print()
{
Person::print();
cout<<"\nPost="<<post<<", Salary ="<<salary;
};

};
int main()
{
Person p1("Pappu","Delhi",55);
Employee e1("Pappu","Delhi",55,"Ex-President",420);
p1.print();
e1.print();
return 0;
}

The basic syntax is
class DerivedClass: access specifier BaseClass

The default access specifier is private.

 

Access rules for Inheritance from derived class.

Inheritance Type  Access for public   Access for protected        Access for private    Type in derived

public                                      Yes                                          Yes                                     No                         public

protected                                 Yes                                         Yes                                     No                         protected

private                                     Yes                                         Yes                                     No                          private

 

 

end

Leave a Reply

Your email address will not be published. Required fields are marked *