Saturday 2 October 2010

INHERITANCE



Inheritance is a process of acquiring the properties of one object to the other object.
(or)
The procedure of creating a new class from one or more existing classes is termed as inheritance.
·         The class that is inherited is called a base class and the inheriting class is called derived class.
·         The base class is also called as super class or parent class or ancestor class.
·         The derived class is also called as sub class or child class or descendent class.
·         It is possible to derive a class from previously derived class. A class can be derived from more than one class.
Example1:
 class A
{
int a, b;
efg();
};

class B: public class A
{
int k, l, m;
xyz();
};


The class A contains the member variables a, b and member functions efg().
The class B contains the member variables and member functions of both class A and class B because the class B is inheriting the class A.
Syntax:
class <child_class_name>: <access specifier> <base class name>
·         Derived class is the new class that is inherited from the base class and it can also have its own members.
·         Access specifier can be either public or private or protected.
·         The members of the base class will be acquired by the way the base class is specified with the access specifier.
·         If no access specifier is specified, then the default specifier will be private.
·         Code reusability feature of Object Oriented Programming is provided by the inheritance mechanism.
·         The size of the child class is always larger than that of the base class.
·         The member functions of base class can be called with respect to the objects derived class.
Example 2:
class A
{
private:
int x;
public:
void setx(int=0)
int getx();
};
class B: public class A  //Class B inherits class A.
{
private:
int y;
public:
void sety(int=0)
int gety();
};
void main()
{

cout<<sizeOf(A);  //display the size of the objects of A
cout<<sizeOf(B)”; //displays the size of the objects of B.
B B1;
B1.setx(1);   //setx() is derived from A
B1.sety(1);
cout<<B1.getx(); //getx() is derived from A
cout<<B1.gety();
}
Types of Inheritance:
The inheritance is divided as following types. They are
1.      Single inheritance
2.      Multiple inheritance
3.      Hierarchical inheritance
4.      Multilevel inheritance
5.      Hybrid inheritance
6.      Multipath inheritance
This depends upon the following points:
·         Number of base classes.
Nested derivation.

No comments:

Post a Comment