Posted By:
4 Jul, 2013 11:01 am PDT

Inheritance in C++

  • What do you mean by inheritance?
  • What is the use of inheritance?
  • What are the different types of inheritance?
Attachment:None


 Inheritance allows as defining a class in terms of another class, which makes it easier to create and maintain a database. This also provides the opportunity to reuse the code.

When creating a class, instead of writing completely new data and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the ‘base’ class and the new class is called the ‘derived’ class.

 

To define a derived class we use the following format:

class derived_class: access_specifier base_class

 

Let us understand more clearly from the following example:

 

#include<iostream.h>

class shape

{

public:

void setwidth(int w)

{

width=w;

}

void setheigth(int h)

{

height=h;

}

protected:

int height,width;

};

class rectangle:public shape

{

public:

int getarea()

{

return (width*height);

};

void main()

{

rectangle rec;

rec.setwidth(10);

cout<<”Total Area:”<<rec.getarea;

}

 

In the above example, class rectangle derives class shape publically. So, public members of the class shape are public in class rectangle and protected members of class shape are protected in class rectangle.

 

Similarly, when deriving from a protected base class, public and protected members of base class becomes protected member of the derived class. And when deriving from a private base class, public and protected members of base class becomes private members of the derived class.

 

A base class’s private members are never accessible directly from a derived class but can be accessed using public and private members.

Was it useful?  




Please login to reply to this problem.