You are on page 1of 4

4/21/2015

FriendshipandinheritanceC++Tutorials
Search:
Tutorials

Go
C++Language

Loggedinas:shyjuu

Friendshipandinheritance

Account

logout

C++
Information
Tutorials
Reference
Articles
Forum

Tutorials
C++Language
AsciiCodes
BooleanOperations
NumericalBases

C++Language
Introduction:
Compilers
BasicsofC++:
Structureofaprogram
Variablesandtypes
Constants
Operators
BasicInput/Output
Programstructure:
Statementsandflowcontrol
Functions
Overloadsandtemplates
Namevisibility
Compounddatatypes:
Arrays
Charactersequences
Pointers
Dynamicmemory
Datastructures
Otherdatatypes
Classes:
Classes(I)
Classes(II)
Specialmembers
Friendshipandinheritance
Polymorphism
Otherlanguagefeatures:
Typeconversions
Exceptions
Preprocessordirectives
Standardlibrary:
Input/outputwithfiles

.NETJobAhmedabad

WebDevelopersWanted@Ahmedabad
1+Yrsexpon.NET/MVC/WCF/Entity

Friendshipandinheritance
Friendfunctions
Inprinciple,privateandprotectedmembersofaclasscannotbeaccessedfromoutsidethesameclassinwhichtheyare
declared.However,thisruledoesnotapplyto"friends".
Friendsarefunctionsorclassesdeclaredwiththefriendkeyword.
Anonmemberfunctioncanaccesstheprivateandprotectedmembersofaclassifitisdeclaredafriendofthatclass.
Thatisdonebyincludingadeclarationofthisexternalfunctionwithintheclass,andprecedingitwiththekeyword
friend:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

//friendfunctions
#include<iostream>
usingnamespacestd;

24
Edit

classRectangle{
intwidth,height;
public:
Rectangle(){}
Rectangle(intx,inty):width(x),height(y){}
intarea(){returnwidth*height;}
friendRectangleduplicate(constRectangle&);
};
Rectangleduplicate(constRectangle&param)
{
Rectangleres;
res.width=param.width*2;
res.height=param.height*2;
returnres;
}
intmain(){
Rectanglefoo;
Rectanglebar(2,3);
foo=duplicate(bar);
cout<<foo.area()<<'\n';
return0;
}

TheduplicatefunctionisafriendofclassRectangle.Therefore,functionduplicateisabletoaccessthememberswidth
andheight(whichareprivate)ofdifferentobjectsoftypeRectangle.Noticethoughthatneitherinthedeclarationof
duplicatenorinitslateruseinmain,memberfunctionduplicateisconsideredamemberofclassRectangle.Itisn't!It
simplyhasaccesstoitsprivateandprotectedmemberswithoutbeingamember.
Typicalusecasesoffriendfunctionsareoperationsthatareconductedbetweentwodifferentclassesaccessingprivateor
protectedmembersofboth.

Friendclasses
Similartofriendfunctions,afriendclassisaclasswhosemembershaveaccesstotheprivateorprotectedmembersof
anotherclass:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

//friendclass
#include<iostream>
usingnamespacestd;

16
Edit

classSquare;
classRectangle{
intwidth,height;
public:
intarea()
{return(width*height);}
voidconvert(Squarea);
};
classSquare{
friendclassRectangle;
private:
intside;
public:
Square(inta):side(a){}
};
voidRectangle::convert(Squarea){
width=a.side;
height=a.side;
}

intmain(){
Rectanglerect;
Squaresqr(4);
rect.convert(sqr);
cout<<rect.area();

http://www.cplusplus.com/doc/tutorial/inheritance/

1/4

4/21/2015

FriendshipandinheritanceC++Tutorials
33 return0;
34 }

Inthisexample,classRectangleisafriendofclassSquareallowingRectangle'smemberfunctionstoaccessprivateand
protectedmembersofSquare.Moreconcretely,RectangleaccessesthemembervariableSquare::side,whichdescribes
thesideofthesquare.
Thereissomethingelsenewinthisexample:atthebeginningoftheprogram,thereisanemptydeclarationofclass
Square.ThisisnecessarybecauseclassRectangleusesSquare(asaparameterinmemberconvert),andSquareuses
Rectangle(declaringitafriend).
Friendshipsarenevercorrespondedunlessspecified:Inourexample,RectangleisconsideredafriendclassbySquare,but
SquareisnotconsideredafriendbyRectangle.Therefore,thememberfunctionsofRectanglecanaccesstheprotected
andprivatemembersofSquarebutnottheotherwayaround.Ofcourse,Squarecouldalsobedeclaredfriendof
Rectangle,ifneeded,grantingsuchanaccess.
Anotherpropertyoffriendshipsisthattheyarenottransitive:Thefriendofafriendisnotconsideredafriendunless
explicitlyspecified.

Inheritancebetweenclasses
ClassesinC++canbeextended,creatingnewclasseswhichretaincharacteristicsofthebaseclass.Thisprocess,known
asinheritance,involvesabaseclassandaderivedclass:Thederivedclassinheritsthemembersofthebaseclass,ontop
ofwhichitcanadditsownmembers.
Forexample,let'simagineaseriesofclassestodescribetwokindsofpolygons:rectanglesandtriangles.Thesetwo
polygonshavecertaincommonproperties,suchasthevaluesneededtocalculatetheirareas:theybothcanbedescribed
simplywithaheightandawidth(orbase).
ThiscouldberepresentedintheworldofclasseswithaclassPolygonfromwhichwewouldderivethetwootherones:
RectangleandTriangle:

ThePolygonclasswouldcontainmembersthatarecommonforbothtypesofpolygon.Inourcase:widthandheight.
AndRectangleandTrianglewouldbeitsderivedclasses,withspecificfeaturesthataredifferentfromonetypeof
polygontotheother.
Classesthatarederivedfromothersinheritalltheaccessiblemembersofthebaseclass.Thatmeansthatifabaseclass
includesamemberAandwederiveaclassfromitwithanothermembercalledB,thederivedclasswillcontainboth
memberAandmemberB.
Theinheritancerelationshipoftwoclassesisdeclaredinthederivedclass.Derivedclassesdefinitionsusethefollowing
syntax:
classderived_class_name:publicbase_class_name
{/*...*/};
Wherederived_class_nameisthenameofthederivedclassandbase_class_nameisthenameoftheclassonwhichitis
based.Thepublicaccessspecifiermaybereplacedbyanyoneoftheotheraccessspecifiers(protectedorprivate).This
accessspecifierlimitsthemostaccessiblelevelforthemembersinheritedfromthebaseclass:Thememberswithamore
accessiblelevelareinheritedwiththislevelinstead,whilethememberswithanequalormorerestrictiveaccesslevel
keeptheirrestrictivelevelinthederivedclass.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

//derivedclasses
#include<iostream>
usingnamespacestd;

20
10

Edit

classPolygon{
protected:
intwidth,height;
public:
voidset_values(inta,intb)
{width=a;height=b;}
};
classRectangle:publicPolygon{
public:
intarea()
{returnwidth*height;}
};
classTriangle:publicPolygon{
public:
intarea()
{returnwidth*height/2;}
};

intmain(){
Rectanglerect;
Triangletrgl;
rect.set_values(4,5);
trgl.set_values(4,5);
cout<<rect.area()<<'\n';
cout<<trgl.area()<<'\n';
return0;
}

TheobjectsoftheclassesRectangleandTriangleeachcontainmembersinheritedfromPolygon.Theseare:width,

http://www.cplusplus.com/doc/tutorial/inheritance/

2/4

4/21/2015

FriendshipandinheritanceC++Tutorials
heightandset_values.
TheprotectedaccessspecifierusedinclassPolygonissimilartoprivate.Itsonlydifferenceoccursinfactwith
inheritance:Whenaclassinheritsanotherone,themembersofthederivedclasscanaccesstheprotectedmembers
inheritedfromthebaseclass,butnotitsprivatemembers.
Bydeclaringwidthandheightasprotectedinsteadofprivate,thesemembersarealsoaccessiblefromthederived
classesRectangleandTriangle,insteadofjustfrommembersofPolygon.Iftheywerepublic,theycouldbeaccessjust
fromanywhere.
Wecansummarizethedifferentaccesstypesaccordingtowhichfunctionscanaccesstheminthefollowingway:
Access

public protected private

membersofthesameclass yes

yes

yes

membersofderivedclass

yes

yes

no

notmembers

yes

no

no

Where"notmembers"representsanyaccessfromoutsidetheclass,suchasfrommain,fromanotherclassorfroma
function.
Intheexampleabove,themembersinheritedbyRectangleandTrianglehavethesameaccesspermissionsastheyhad
intheirbaseclassPolygon:
1
2
3
4
5

Polygon::width//protectedaccess
Rectangle::width//protectedaccess
Polygon::set_values()//publicaccess
Rectangle::set_values()//publicaccess

Thisisbecausetheinheritancerelationhasbeendeclaredusingthepublickeywordoneachofthederivedclasses:
classRectangle:publicPolygon{/*...*/}

Thispublickeywordafterthecolon(:)denotesthemostaccessiblelevelthemembersinheritedfromtheclassthat
followsit(inthiscasePolygon)willhavefromthederivedclass(inthiscaseRectangle).Sincepublicisthemost
accessiblelevel,byspecifyingthiskeywordthederivedclasswillinheritallthememberswiththesamelevelstheyhadin
thebaseclass.
Withprotected,allpublicmembersofthebaseclassareinheritedasprotectedinthederivedclass.Conversely,ifthe
mostrestrictingaccesslevelisspecified(private),allthebaseclassmembersareinheritedasprivate.
Forexample,ifdaughterwereaclassderivedfrommotherthatwedefinedas:
classDaughter:protectedMother;

ThiswouldsetprotectedasthelessrestrictiveaccesslevelforthemembersofDaughterthatitinheritedfrommother.
Thatis,allmembersthatwerepublicinMotherwouldbecomeprotectedinDaughter.Ofcourse,thiswouldnotrestrict
Daughterfromdeclaringitsownpublicmembers.Thatlessrestrictiveaccesslevelisonlysetforthemembersinherited
fromMother.
Ifnoaccesslevelisspecifiedfortheinheritance,thecompilerassumesprivateforclassesdeclaredwithkeywordclass
andpublicforthosedeclaredwithstruct.

Whatisinheritedfromthebaseclass?
Inprinciple,aderivedclassinheritseverymemberofabaseclassexcept:
itsconstructorsanditsdestructor
itsassignmentoperatormembers(operator=)
itsfriends
itsprivatemembers
Althoughtheconstructorsanddestructorsofthebaseclassarenotinheritedasconstructorsanddestructorsinthe
derivedclass,theyarestillcalledbythederivedclass'sconstructor.Unlessotherwisespecified,theconstructorsofderived
classescallthedefaultconstructorsoftheirbaseclasses(i.e.,theconstructortakingnoarguments),whichmustexist.
Callingadifferentconstructorofabaseclassispossible,usingthesamesyntaxastoinitializemembervariablesinthe
initializationlist:
derived_constructor_name(parameters):base_constructor_name(parameters){...}
Forexample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//constructorsandderivedclasses
#include<iostream>
usingnamespacestd;
classMother{
public:
Mother()
{cout<<"Mother:noparameters\n";}
Mother(inta)
{cout<<"Mother:intparameter\n";}
};

Mother:noparameters
Daughter:intparameter

Edit

Mother:intparameter
Son:intparameter

classDaughter:publicMother{
public:
Daughter(inta)
{cout<<"Daughter:intparameter\n\n";}
};

http://www.cplusplus.com/doc/tutorial/inheritance/

3/4

4/21/2015

FriendshipandinheritanceC++Tutorials
19
20
21
22
23
24
25
26
27
28
29
30

classSon:publicMother{
public:
Son(inta):Mother(a)
{cout<<"Son:intparameter\n\n";}
};
intmain(){
Daughterkelly(0);
Sonbud(0);

return0;
}

NoticethedifferencebetweenwhichMother'sconstructoriscalledwhenanewDaughterobjectiscreatedandwhich
whenitisaSonobject.ThedifferenceisduetothedifferentconstructordeclarationsofDaughterandSon:
1 Daughter(inta)//nothingspecified:calldefaultconstructor
2 Son(inta):Mother(a)//constructorspecified:callthisspecificconstructor

Multipleinheritance
Aclassmayinheritfrommorethanoneclassbysimplyspecifyingmorebaseclasses,separatedbycommas,inthelistof
aclass'sbaseclasses(i.e.,afterthecolon).Forexample,iftheprogramhadaspecificclasstoprintonscreencalled
Output,andwewantedourclassesRectangleandTriangletoalsoinherititsmembersinadditiontothoseofPolygonwe
couldwrite:
1 classRectangle:publicPolygon,publicOutput;
2 classTriangle:publicPolygon,publicOutput;

Hereisthecompleteexample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

//multipleinheritance
#include<iostream>
usingnamespacestd;

20
10

Edit

classPolygon{
protected:
intwidth,height;
public:
Polygon(inta,intb):width(a),height(b){}
};
classOutput{
public:
staticvoidprint(inti);
};
voidOutput::print(inti){
cout<<i<<'\n';
}
classRectangle:publicPolygon,publicOutput{
public:
Rectangle(inta,intb):Polygon(a,b){}
intarea()
{returnwidth*height;}
};
classTriangle:publicPolygon,publicOutput{
public:
Triangle(inta,intb):Polygon(a,b){}
intarea()
{returnwidth*height/2;}
};

intmain(){
Rectanglerect(4,5);
Triangletrgl(4,5);
rect.print(rect.area());
Triangle::print(trgl.area());
return0;
}

Previous:
Specialmembers

Index

Next:
Polymorphism

Homepage|Privacypolicy
cplusplus.com,20002015Allrightsreservedv3.1
Spottedanerror?contactus

http://www.cplusplus.com/doc/tutorial/inheritance/

4/4

You might also like