Wednesday 8 April 2015

Single Inheritance


A derived class inherits data members and member functions, but not the constructor or destructor from its base class. The inheritance will be two types they are

? Private inheritance
? Public inheritance

Public inheritance

Sample Program

#include <iostream.h>
class Bird
{
private:
int wlength;
int weight;
public:
void setbird(int w, int wt)
{
wlength = w;
weight = wt;
}
void showwing(void)
{
cout<<”My wing length is “<<wlength<<”inches”<<endl;
cout<<”My weight is<<weight<<”Kgs”<<endl;
}
};
class Parrot:public Bird
{
private:
char color[10];
public:
void showpro(void)
{
cout<<”I can talk”<<endl;
}
};
void main()
{
Parrot P1, P2;
P2.setbird(15,3);
P1.showwing();
P1.showpro();
P2.showwing();
P2.showpro();
}


Private Inheritance

Sample Program

#include <iostream.h>
Class B
{
int a;
public:
int b;
void get_ab(void);
int get_a(void);
void show_a(void);
};
class D : private B
{
int c;
public:
void mul(void);
void display(void);
};
void B::get_ab(void)
{
cout<<”Enter the values for a and b”;
cin>>a>>b;
}
int B::get_a(void)
{
return a;
}
void B::show_a(void)
{
cout<<”a = “<<a<<endl;
}
void D::mul(void)
{
get_ab();
c = b * get_a();
}
void D::display(void)
{
show_a();
cout<<”b = “<<b<<endl;
cout<<”c = “<<c<<endl;
}
void main()
{
D d;
d.mul();
d.display();
// d.b = 20 wront will not work
d.mul();
d.display();
}

No comments:

Post a Comment