Login    New User    Forgot Password    Help      

Inheritance in C++

GO TO INDEX

Inheritance in C++

Inheritance is the concept that when a class of object is defined, any subclass that is defined can inherit the definitions of one or more general classes. This means for the programmer that an object in a subclass need not carry its own definition of data and methods that are generic to the class (or classes) of which it is a part. This not only speeds up program development; it also ensures an inherent validity to the defined subclass object (what works and is consistent about the class will also work for the subclass). The simple example in C++ is having a class that inherits a data member from its parent class.
class A 
{ 
public: 
integer d; 
}; 
class B : public A 
{ 
public: 
}; 
The class B in the example does not have any direct data member does it? Yes, it does. It inherits the data member d from class A. When one class inherits from another, it acquires all of its methods and data. We can then instantiate an object of class B and call into that data member.

Example

#include<iostream.h>  
#include<conio.h>  
class B  
{  
int a; 
public:  int b;  
void get_ab();  
int get_a();  
void show_a();  
};  

class D: private B  
{  
int c;  
public:  
void mul();  
void display();  
};  

void B::get_ab()  
{  
cout<<"Enter Values for a and b";  
cin>>a>>b;  
}  

int B::get_a()  
{  return a;  }  

void B::show_a()
{  			
cout<<"a= "<<a<<"\n";  		
}  

void D::mul()  
{  			
get_ab();  		
c=b*get_a();         
}  

void D:: display()
{  
show_a();  
cout<<"b= "<<b<<"\n";  
cout<<"c= "<<c<<"\n\n";  
}  

void main()  
{  			
clrscr();
D d;  		
d.mul();
d.display();  		
d.mul();  			
d.display();  		
getch();  	
}

OUTPUT

A=5
A=5
B=10
C=50
A=5
B=20
C=100

GO TO INDEX