Top Banner
Inheritance Inheritance It is the mechanism of It is the mechanism of deriving new class from deriving new class from existing class.It existing class.It provides the idea of provides the idea of reusability. reusability. A B Base , super,parent class derived , sub, child class
40

inhertance c++

May 06, 2015

Download

Education

abhilashagupta

It is nice ppt. It will be helpful for u.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: inhertance c++

InheritanceInheritanceIt is the mechanism of It is the mechanism of

deriving new class from deriving new class from existing class.It provides the existing class.It provides the

idea of reusability.idea of reusability.A

B

Base , super,parent class

derived , sub, child class

Page 2: inhertance c++

Types of inheritanceTypes of inheritance

Single levelSingle level

B

A

Multilevel Multiple

Hierarchical hybrid

B

A

C

A B

C

A

B C D

E F G H I J

B

A

C

B A B

C

C

Page 3: inhertance c++

PublicPublic members provides lowest members provides lowest security and it can be accessed in security and it can be accessed in whole programme.whole programme.

PrivatePrivate members are visible only to members are visible only to class.It provides the highest security.class.It provides the highest security.

ProtectedProtected members has middle members has middle security and it is visible to the class security and it is visible to the class and classes derived from class. It is and classes derived from class. It is not accessible in mainnot accessible in main

Page 4: inhertance c++

syntaxsyntax Class classname: Class classname: modemode oldclassname oldclassname

Mode:Mode: PublicPublic : inherit all member as in base : inherit all member as in base

class mode(public to public and class mode(public to public and private to private).private to private).

PrivatePrivate:: all members of base class all members of base class become private to derived class.become private to derived class.

ProtectedProtected:: all members of base class all members of base class become protected to derived class.become protected to derived class.

Page 5: inhertance c++

Class baseClass base {{ Private:Private: Int x;Int x; Protected:Protected: Int y;Int y; Public:Public: Int z;Int z; };}; Class der1:public baseClass der1:public base {{ Public:Public: Void get()Void get() {{ Int o;Int o; o=x; //error not o=x; //error not

accessibleaccessible o=y; // ok o=y; // ok o=z; //oko=z; //ok }} };};

Class der2:private base{Public:Void get(){Int p;p=x; //error not accessiblep=y; // ok p=z; //ok}};

Void main(){Int M;der1 d1;M=d1.x; //errorM=d1.y; //errorM=d1.z; //okder2 d2;M=d2.x; //errorM=d2.y; // errorM=d2.z; //error}

Page 6: inhertance c++

Single level inheritanceSingle level inheritance #include<iostream.h>#include<iostream.h> Class baseClass base {{ Public:Public: display()display() {{ Cout<<“It is base class”;Cout<<“It is base class”; }} };}; Class derived:public baseClass derived:public base {{ };}; Void main()Void main() {{ Derived d;Derived d; d.display();d.display(); }}

Page 7: inhertance c++

#include<iostream.h>#include<iostream.h>

Class baseClass base

{{

Int x;Int x;

Public:Public:

Get_base(int a)Get_base(int a)

{{

X=a;X=a;

}}

Display_base()Display_base()

{{

Cout<<“x=“<<x;Cout<<“x=“<<x;

}}

};};

Class derived:public base{Int y;Public:Get_derived(int a){y=a;}Display_derived(){Cout<<“y=“<<y;}};

Void main(){derived d;d.Get_base(10);d.Dispaly_base();d.Get_derived(20);d.Dispaly_derived();}

Page 8: inhertance c++

#include<iostream.h#include<iostream.h>>

Class baseClass base

{{

int x;int x;

Public:Public:

Get_base(int a)Get_base(int a)

{{

X=a;X=a;

}}

Display_base()Display_base()

{{

Cout<<“x=“<<x;Cout<<“x=“<<x;

}}

};};

Class derived:public base{Int y;Public:Get_derived(int a){Get_base(40);y=a;}Display_derived(){Display_base();Cout<<“y=“<<y;}};

Void main(){derived d;d.Get_derived(10);d.Dispaly_derived();}

Page 9: inhertance c++

Private inheritancePrivate inheritance#include<iostream.h#include<iostream.h

>>

Class baseClass base

{{

Public:Public:

Display_base()Display_base()

{{

Cout<<“It is base Cout<<“It is base class”;class”;

}}

};};

Class derived:private base{};Void main(){derived d;d.Dispaly_base();}

o/p ------ error

Page 10: inhertance c++

Class baseClass base {{ Int x;Int x; Public:Public: Get_base(int a)Get_base(int a) {{ X=a;X=a; }} Display_base()Display_base() {{ Cout<<“x=“<<x;Cout<<“x=“<<x; }} };};

Class derived:private base{Int y;Public:Get_derived(int a){Get_base(20);y=a;}Display_derived(){Display_base();Cout<<“y=“<<y;}};

Void main(){derived d;d.Get_derived(10);d.Dispaly_derived();}

Page 11: inhertance c++

Function overridingFunction overriding

Page 12: inhertance c++

#include<iostream.h>#include<iostream.h> Class baseClass base {{ Int x;Int x; Public:Public: Getdata(int a)Getdata(int a) {{ X=a;X=a; }} Display ()Display () {{ Cout<<“x=“<<x;Cout<<“x=“<<x; }} };};

Class derived:public base{Int y;Public:Getdata(int a){y=a;}Display(){Cout<<“y=“<<y;}};

Void main(){derived d;d.Getdata();d.Dispaly();}

o/p--- y =

Page 13: inhertance c++

#include<iostream.h>#include<iostream.h> Class areaClass area {{ Protected:Protected: Int length,width;Int length,width; Public:Public: Void getdata()Void getdata() {{ Cout<<“enter length and width”.;Cout<<“enter length and width”.; Cin>>length>>width;Cin>>length>>width; }} };}; Class volume :public areaClass volume :public area {{ Int height;Int height; Public:Public: Void get()Void get() {{ Getdata();Getdata(); Cout<<“enter height”;Cout<<“enter height”; Cin>>height;Cin>>height; }} Void cal_volume()Void cal_volume() {{ Cout<<“volume=“<<length*heighCout<<“volume=“<<length*heigh

t*width;t*width; }} };};

void main(){Volume v;v.get();v.cal_volume();}

Page 14: inhertance c++

#include<iostream.h>#include<iostream.h> Class areaClass area {{ Protected:Protected: Int length,width;Int length,width; Public:Public: Void getdata()Void getdata() {{ Cout<<“enter len and Cout<<“enter len and

width”;width”; }} };}; Class volume :public areaClass volume :public area {{

Public:Public: Int height;Int height; Void get()Void get() {{ Getdata();Getdata(); Cout<<“enter height”;Cout<<“enter height”; Cin>>height;Cin>>height; }} };};

void main(){Volume v;v.get();Int vol=length*height*width;Cout<<“volume=“<<vol;}

o/p === error (protected member can be accessed in that class and in derived class not in main)

Page 15: inhertance c++

Multilevel inheritanceMultilevel inheritance#include<iostream.h>#include<iostream.h>Class firstClass first{{Public:Public:Display1()Display1(){{Cout<<“first class”;Cout<<“first class”;}}};};Class second:public firstClass second:public first{{Public:Public:Display2()Display2(){{Cout<<“second class”;Cout<<“second class”;}}};};

Class third:public second{Public:Display3(){Cout<<“third class”;}};Void main(){third t;t.Display1();t.Display2();t.Display3();

}

Page 16: inhertance c++

Multiple inheritanceMultiple inheritance #include<iostream.h>#include<iostream.h> Class superClass super {{ Protected:Protected: int base;int base; Void getbase()Void getbase() {{ Cout<<“enter base”;Cout<<“enter base”; Cin>>base;Cin>>base; }} };}; Class sub:public superClass sub:public super {{ Protected:Protected: Int power:Int power: Void getpower()Void getpower() {{ Cout<<“enter Cout<<“enter

power”;power”; Cin>>power;Cin>>power; }} };};

Class result:public super,public:sub{Public:Void show(){getbase();getpower();Int t=1;for(int i=1;i<=power;i++){t=t*base;}Cout<<“base=“<<base;Cout<<“power=“<<power;Cout<<“output result=“<<t;}};

Void main(){Result t;t.show();}

Page 17: inhertance c++

Hierarchical inheritanceHierarchical inheritance

a

b c d

e f g hi j

Page 18: inhertance c++

#include<iostream.h>#include<iostream.h>#include<string.h>#include<string.h>Class universityClass university {{Protected:Protected:Char uname[20];Char uname[20];Public:Public: void getuniversity()void getuniversity() {{ Strcpy(uname,”RTU”);Strcpy(uname,”RTU”); }} };};

Class college1: public universityClass college1: public university{{Protected:Protected:Char college_name[20]Char college_name[20]Public:Public: college1()college1() {{ Strcpy(college_name,”I.E.T”);Strcpy(college_name,”I.E.T”); }}Void display1()Void display1(){{Cout<<“college Cout<<“college

name=<<college_name;name=<<college_name;Cout<<“university Cout<<“university

name=<<uname;name=<<uname;}} };};

Class college2: public university{Protected:Char college_name[20];Public: college2(){ Strcpy(college_name,”A.I.E.T”); }Void display2(){Cout<<“college name=<<college_name;Cout<<“university name=<<uname;} };Void main(){University u;u.getuniversity();College1 c1;C1.display1();College2 c2;C2.display2();}

Page 19: inhertance c++

HybridHybrid

studentstudent

Test sports

result

Page 20: inhertance c++

class studentclass student{{private :private :int rn;int rn;char na[20];char na[20];public:public:void getdata()void getdata(){{cout< < "Enter Name And Roll No : ";cout< < "Enter Name And Roll No : ";cin>>na>>rn;cin>>na>>rn;}}void putdata()void putdata(){{cout< < endl< < na< < "\t"< < rn< < "\cout< < endl< < na< < "\t"< < rn< < "\t";t";}}};};

class test : public studentclass test : public student{{protected:protected:float m1,m2;float m1,m2;public:public:void gettest()void gettest(){{cout< < endl< < "Enter your marks In CP cout< < endl< < "Enter your marks In CP 1 And Cp 2 :";1 And Cp 2 :";cin>>m1>>m2;cin>>m1>>m2;}}void puttest()void puttest(){{cout< < m1< < "\t"< < m2< < "\t";cout< < m1< < "\t"< < m2< < "\t";}}};};

class sports{protected:float score;public:void getscore(){cout< < endl< < "Enter your score :";cin>>score;}void putscore(){cout< < score< < "\t";}};class results : public test , public sports{private :float total;public :void putresult(){total = m1+m2+score;cout< < total;}};

Page 21: inhertance c++

void main()void main(){{results r[5];results r[5];clrscr();clrscr();for(int i=0;i< 5;i++)for(int i=0;i< 5;i++){{r[i].getdata();r[i].getdata();r[i].gettest();r[i].gettest();r[i].getscore();r[i].getscore();}}cout< < endl< < "Name\tRollno\tCP 1\tCP 2\cout< < endl< < "Name\tRollno\tCP 1\tCP 2\tScore\tTotal“; for(i=0;i< 5;i++)tScore\tTotal“; for(i=0;i< 5;i++){{r[i].putdata();r[i].putdata();r[i].puttest();r[i].puttest();r[i].putscore();r[i].putscore();r[i].putresult();r[i].putresult();}}getch();getch();} }

Page 22: inhertance c++

2nd example of hybrid:2nd example of hybrid: PROBLEM:?PROBLEM:? Animals->MammalsAnimals->Mammals Animals>ReptilesAnimals>Reptiles MammalsMammals, , ReptilesReptiles ->Snakes ->Snakes

SO DUPLICATION FROM B AND C TO SO DUPLICATION FROM B AND C TO D CLASS SO IT CONFUSES THE D CLASS SO IT CONFUSES THE COMPILER AND IT DISPLAYS ERRORCOMPILER AND IT DISPLAYS ERROR

Animals

Mammals Reptiles

Snakes

Page 23: inhertance c++

SOLUTION OF IT: VIRTUALSOLUTION OF IT: VIRTUAL

class aclass a{{};};class b:public aclass b:public a{ };{ };class c:public aclass c:public a{ };{ };class d: public b, public cclass d: public b, public c{ };{ };

VIRTUAL BASE CLASS

class a{};class b:public virtual a{};class c:virtual public a{ };class d: public b, public c{ };

B and C share the same subobject of A. Using the keyword virtual in this example ensures that an object of class D inherits only one subobject of class A

//ERROR

Page 24: inhertance c++

Class aClass a {{ Public:Public: Void show( )Void show( ) {{ Cout<<“It is base Cout<<“It is base

class”;class”; }} };}; Class b:virtual public aClass b:virtual public a { };{ }; Class c:virtual public aClass c:virtual public a { };{ }; Class d:public b,public cClass d:public b,public c { };{ };

Void main(){D obj;Obj.show();}

o/p: It is base class

Page 25: inhertance c++

Constructor and destructor in Constructor and destructor in inheritanceinheritance

Constructor:Constructor: first first basebase class class then then derived derived class class constructor is called.constructor is called.

Destructor:Destructor: Reverse(first Reverse(first derivedderived class then class then base base class class destructor is called).destructor is called).

Page 26: inhertance c++

Constructor and destructor in Constructor and destructor in inheritanceinheritanceClass baseClass base

{{Public:Public:Base()Base(){{Cout<<“it is base class<<endl”;Cout<<“it is base class<<endl”;}}};};Class derived:public baseClass derived:public base{{Public:Public:derived()derived(){{Cout<<“it is derived class”;Cout<<“it is derived class”;}}

Void main(){Derived d;}

O/P it is base classit is derived class

Page 27: inhertance c++

Destructor in inheritanceDestructor in inheritance

Called in reverse orderCalled in reverse order

Page 28: inhertance c++

Class baseClass base{{Public:Public:Base()Base(){{Cout<<“it is base class constructor<<endl”;Cout<<“it is base class constructor<<endl”;}}~Base()~Base(){{Cout<<“it is base class destructor<<endl”;Cout<<“it is base class destructor<<endl”;}}

};};Class derived:public baseClass derived:public base{{Public:Public:derived()derived(){{Cout<<“it is derived class Cout<<“it is derived class

constructor<<endl”;constructor<<endl”;}}~derived()~derived(){{Cout<<“it is derived class destructor<<endl”;Cout<<“it is derived class destructor<<endl”;}}};};

Void main(){Derived d;}

o/p : it is base class constructorit is derived class constructorit is derived class destructorit is base class destructor

Page 29: inhertance c++

Explicitly calling constructorExplicitly calling constructorClass baseClass base{{Public:Public:Base()Base(){{Cout<<“it is base class Cout<<“it is base class

constructor<<endl”;constructor<<endl”;}}~Base()~Base(){{Cout<<“it is base class Cout<<“it is base class

destructor<<endl”;destructor<<endl”;}}

};};Class derived:public baseClass derived:public base{{Public:Public:

derived() derived() :base():base(){{Cout<<“it is derived class Cout<<“it is derived class

constructor<<endl”;constructor<<endl”;}}

~derived(){Cout<<“it is derived class destructor<<endl”;}};Void main(){Derived d;}

o/p : it is base class constructorit is derived class constructorit is derived class destructorit is base class destructor

Page 30: inhertance c++

Constructor and destructor in Constructor and destructor in multilevelmultilevel

Page 31: inhertance c++

Class baseClass base{{Public:Public:Base()Base(){{Cout<<“it is base class Cout<<“it is base class

constructor<<endl”;constructor<<endl”;}}~Base()~Base(){{Cout<<“it is base class Cout<<“it is base class

destructor<<endl”;destructor<<endl”;}}

};};Class derived1:public baseClass derived1:public base{{Public:Public:derived1()derived1(){{Cout<<“it is derived1 class Cout<<“it is derived1 class

constructor<<endl”;constructor<<endl”;}}~derived1()~derived1(){{Cout<<“it is derived1 class Cout<<“it is derived1 class

destructor<<endl”;destructor<<endl”;}}};};

Class derived2:public derived1{Public:derived(){Cout<<“it is derived2 class constructor<<endl”;}~derived(){Cout<<“it is derived2 class destructor<<endl”;}};

Void main(){Derived2 obj;}o/p:

it is base class constructorit is derived1 class constructorit is derived2 class constructorit is derived2 class destructorit is derived1 class destructorit is base class destructor

Page 32: inhertance c++

Constructor and destructor in Constructor and destructor in multiple inheritancemultiple inheritance

Constructor is called in the sequence of inheritance

Class a{ };Class b{ };

Class c: public b,public a{};Then first constructor of b then of a is called

Page 33: inhertance c++

Class base1Class base1{{Public:Public:Base()Base(){{Cout<<“it is base1 class Cout<<“it is base1 class

constructor<<endl”;constructor<<endl”;}}

};};Class base2Class base2{{Public:Public:base2()base2(){{Cout<<“it is base2Cout<<“it is base2 class constructor<<endl”;class constructor<<endl”;}}};};

Class derived:public base2,public base1{Public:derived(){Cout<<“it is derived class constructor<<endl”;}};

Void main(){Derived d;}

o/p:it is base2 class constructorit is base1 class constructorit is derived class constructor

Page 34: inhertance c++

Class base1Class base1{{Public:Public:Base()Base(){{Cout<<“it is base1 class Cout<<“it is base1 class

constructor<<endl”;constructor<<endl”;}}

};};Class base2Class base2{{Public:Public:base2()base2(){{Cout<<“it is base2Cout<<“it is base2 class constructor<<endl”;class constructor<<endl”;}}};};

Class derived:public base2,public base1{Public:derived():base1(),base2(){Cout<<“it is derived class constructor<<endl”;}};

Void main(){Derived d;}

o/p:it is base2 class constructorit is base1 class constructorit is derived class constructor

Same output even done explicit calling

Page 35: inhertance c++

Class baseClass base{{Int x;Int x;Public:Public:base(int a)base(int a){{X=a;X=a;Cout<<“x=“<<x<<endl;Cout<<“x=“<<x<<endl;}};}};Class derived:public baseClass derived:public base{{ int y;int y;Public:Public:derived(int l,int m):derived(int l,int m):base(l)base(l){{y=m;y=m;Cout<<“y=“<<y;Cout<<“y=“<<y;}}};};

Void main( ){Derived d(20,30);}

o/p X=20Y=30

Page 36: inhertance c++

Initialize the values of data Initialize the values of data members from constructor members from constructor

Class demoClass demo{{ int x,y;int x,y;Public:Public:demo(int l,int m):demo(int l,int m):x(l),y(m)x(l),y(m){{Cout<<“x=“<<x<<endl<<“y=“<<y;Cout<<“x=“<<x<<endl<<“y=“<<y;}}};};

Void main(){Demo d;}

Page 37: inhertance c++

ContainershipContainership If we create the object of one class into If we create the object of one class into

another class and that object will be a another class and that object will be a member of the class.then it is called member of the class.then it is called containership.containership.

This relation is calles This relation is calles has_a has_a relation.relation. While the inheritance is called While the inheritance is called kind_of kind_of

andand is_a is_a Relation.Relation.

Page 38: inhertance c++

Class upperClass upper{{Public:Public:Void display()Void display(){{Cout<<“hello”<<endl;Cout<<“hello”<<endl;}}};};Class lowerClass lower{{Upper obj;Upper obj;Public:Public:Lower()Lower(){{Obj.display();Obj.display();}}

};};

Void main(){Lower l;}

o/phello

Page 39: inhertance c++

Container class also call upper Container class also call upper class constructor first like class constructor first like inheritance.It can use only inheritance.It can use only public member of upper class public member of upper class not the private and protected not the private and protected membersmembers

Page 40: inhertance c++

Class upperClass upper{{Public:Public:upper()upper(){{Cout<<“it is upper class Cout<<“it is upper class

constructorconstructor<<endl”;<<endl”;}}

};};Class lowerClass lower{{Upper obj;Upper obj;Public:Public:lower()lower(){{Cout<<“it is lower class Cout<<“it is lower class

constructorconstructor<<endl”;<<endl”;}}};};

Void main(){lower l;}

o/p

it is upper class constructorit is lower class constructor