CM505.36 1 OBJECTIVE On completion of this period, you would be able to know Necessity of Inheritance Relation between base class and derived class
CM505.36 2 Inheritance Acquiring the properties of one class to another class is inheritance.
CM505.36 3 Necessity for inheritance Reusability We can derive a new class from an existing one and add new features to it.
CM505.36 4 Necessity for inheritance Another major reason for inheriting is the capability to express the inheritance relationship which ensure the closeness with the real world. And one of the other reason is transitive nature.
CM505.36 5 Relation between base class & derived class Inheritance is the process of creating a new class called derived class from the existing class called base class. The derived class inherits all the capabilities of the base class.The base class remains unchanged.
CM505.36 6 Relation between base class and derived class Feature A Feature B Feature C Feature B Feature C Feature A Feature D Base Class (Existing Class) Derived Class (New Class) Defined In Derived class Derived in base Class and also Accessible from Derived class Fig .1
CM505.36 7 Relation between base class and derived class The derived class inherits the features of the base class A, B and C and adds its own features D. The arrow in the diagram symbolizes derived from.
CM505.36 8 Relation between base class and derived class A base class is also called parent class or super class A derived class is also called child class or subclass. A derived class may itself be base class from which the additional classes are derived.
CM505.36 9 Relation between base class and derived class DERIVED CLASS: The declaration of derived class is as that same of ordinary class. A derived class contains of the following components
CM505.36 10 Relation between base class and derived class DERIVED CLASS: The keyword class The name of the Derived class A single colon
CM505.36 11 Relation between base class and derived class DERIVED CLASS: The type of derivation (private, public or protected) The name of the base or parent class The reminder of the class definition
CM505.37to38 12 Access control or visibility mode: The three types of access control or visibility modes are: public private protected Pre requisite
CM505.37to38 13 Syntax for defining a derived class Syntax: class derived_classname : visibilitymode base_classname { ……………… ……………… Members of derived class };
CM505.37to38 14 Relation between base class and derived class Syntax: class derived_classname : visibilitymode base_classname { ……………… ……………… Members of derived class } ;
CM505.37to38 15 Syntax for defining a derived class The colon indicates that the derived class name is derived from the base class name. The visibility mode is optional.i.e it may be public or private. The default visibility mode specifies the features are private. contd..
CM505.37to38 16 Syntax for defining a derived class Example: class A { ………………….}members of base class A }; class x : public A { ……………}members of derived class X }; contd..
CM505.37to38 17 Access control or visibility mode The three types of access control or visibility modes are: public private protected
CM505.37to38 18 Access control or visibility mode Public: The public derivation means that the derived class can access the public and protected members of the base class but not the private members of base class contd..
CM505.37to38 19 Access control or visibility mode Public: The public members of the base class becomes public members of the derived access specified for inherited members in the derived class. contd..
CM505.37to38 20 Access control or visibility mode Public Member of a class: The members of a class, which are to be visible outside the class . Public members should be declared in public section only. contd..
CM505.37to38 21 Access control or visibility mode Public Member of a class: All the members and functions can be declared in public section they can be accessed without any restriction from any where in the program. contd..
CM505.37to38 22 Access control or visibility mode Public Member of a class: Either by function that belong to the class or by those external to the class. contd..
CM505.37to38 23 Access control or visibility mode Public Member of a class Example: class person { public: int age; int get age() { } }; contd..
CM505.37to38 24 Access control or visibility mode Private : The private derivation means that the derived class can access the public and protected members of the base class. contd..
CM505.37to38 25 Access control or visibility mode Private: The public, protected members of the base class becomes private members of derived class. i.e the inheritance becomes private in the derived class. They cannot be inherited further. contd..
CM505.37to38 26 Access control or visibility mode Private Member of a class: The private member of a class have strict access control. Only the member functions of the same class can access these members. The private members of a class are inaccessible outside the class. contd..
CM505.37to38 27 Access control or visibility mode Private Member of a class: Thus providing a mechanism for preventing accidental modifications of the data members. Information hidden is implemented. The private members can still accessed. contd..
CM505.37to38 28 Access control or visibility mode Private Member of a class: Access control in c++ has objective of reducing the likelihood of bugs and enhancing consistency. contd..
CM505.37to38 29 Access control or visibility mode Private Member of a class: The class should have at least one member that is not private. contd..
CM505.37to38 30 Access control or visibility mode Private Member of a class: Example: class person { private: int age; int get age() { } }; contd..
CM505.37to38 31 Access control (or) visibility mode Protected : The protected derivation means that the derived class can access the public and private members of the base class. public protected numbers the base class become protected numbers in the derived class. contd..
CM505.37to38 32 Access control (or) visibility mode Protected Member of a class : The access control of the members is similar to that of private members. Protected members has more significance in inheritance. contd..
CM505.37to38 33 Access control (or) visibility mode Protected Member of a class: The protected members of a class have strict access these members. Providing a mechanism for preventing accidental modifications of the data members. contd..
CM505.37to38 34 Access control (or) visibility mode Protected Member of a class: Only the member functions of same class can access these members. The protected members of a class are inaccessible outside the class. contd..
CM505.37to38 35 Access control (or) visibility mode Protected Member of a class: Information hiding is implemented. The protected members can still be accessed. contd..
CM505.37to38 36 Access control (or) visibility mode Protected Member of a class: Example: class person { protected: int age; int get age() { } }; contd..
CM505.37to38 37 Access control (or) visibility mode Inheritance type case class derived class private public protected private numbers public numbers Protected numbers private numbers public numbers protected numbers private numbers protected numbers public numbers not inherited private numbers private numbers not inherited public numbers protected numbers not inherited protected numbers protected numbers contd..
CM505.39 38 Inheritance The inheritance is classified as Single inheritance Multiple inheritance Multilevel inheritance Hierarchical inheritance Hybrid inheritance
CM505.39 39 Inheritance Single inheritance : A single inheritance contains only one derived class and one base class.
CM505.39 40 Single Inheritance BASE CLASS DERIVED CLASS
CM505.39 41 Multi level inheritance more than one level of inheritance base class Derived class Derived class level/1 level/2
CM505.39 42 Multiple Inheritance A derived class with several base classes is known as multiple inheritance.
CM505.39 43 BASE CLASS 1 BASE CLASS 2 DERIVED CLASS Multiple Inheritance
CM505.39 44 Hierarchical Inheritance The properties of one class may be inheritance by more than one class. This process is known as Hierarchical Inheritance.
CM505.39 45 BASE CLASS DERIVED CLASS DERIVED CLASS DERIVED CLASS Hierarchical Inheritance
CM505.39 46 Hybrid Inheritance The combination of multilevel & multiple inheritance is know as hybrid inheritance.
CM505.39 47 BASE CLASS 1 DERIVED CLASS1 DERIVED CLASS2 BASE CLASS 2 Hybrid Inheritance
Types of Derivation The class can be derived in three visibility modes public private protected 48
Public Derivation When a class is derived in the public mode it does not change the mode of the inherited members in the derived class. The public members remain public and protected members remain protected for the derived class in public inheritance. 49
Private Derivation When a class is derived in the private mode it changes the mode of the inherited members in the derived class. The public and protected members become the private members for the derived class. So the inherited members can be accessed only through the member functions of the derived class. 50
Protected Derivation When a class is derived in protected mode it changes the mode of the inherited members in the derived class. The public and protected members become the protected members for the derived class in protected inheritance. So the inherited members can be accessed only through the member functions of the derived class. 51
52 C++ Syntax: public derivation class DerivedClass : public BaseClass { private: int y; public: void setY ( int y_in ) {y= y_in ;} int getY (){ cout <<y;} } A derived class. The colon operator means the derived class inherits from the base class
53 C++ Syntax: public derivation class DerivedClass : public BaseClass { private: int y; public: void setY ( int y_in ) {y= y_in ;} int getY () { cout <<y;} } the public derivation means that objects of the derived class can access the public methods and attributes of the base class This is the most usual type of derivation
54 C++ Syntax: public derivation class BaseClass { private: int x; public: void setX ( int x_in ) {x= x_in ;} int getX () { cout <<x;} } class DerivedClass : public BaseClass { private: int y; public: void setY ( int y_in ){y= y_in ;} int getY (){ cout <<y;} } main () { BaseClass base_object ; DerivedClass derived_object ; base_object.setX (7); derived_object.setX (12); derived_object.setY (1); base_object.getX (); derived_object.getY (); derived_object.getX (); return 0; } Object of the derived class can access methods of the derived class and also methods of the base class
55 C++ Syntax: private derivation class DerivedClass: private BaseClass { private: int y; public: void setY(int y_in); int getY(); } Another derived class - the private derivation means that objects of the derived class can’t access the public methods and attributes of the base class - but the methods of the derived class can! This is the least common type
56 C++ Syntax: the ‘protected’ keyword An object of a publicly derived class can access the public methods of the base class, but not the private attributes Changing the private keyword in the base class to protected makes the attributes available to derived classes
Access Specifiers Access Specifier Accessible from own class Accessible from derived class Accessible from objects from outside the class public Yes Yes Yes protected Yes Yes No private Yes No No 57
Effect of inheritance on the visibility of member 58
59 C++ Syntax: inheriting destructors Constructors are not inherited. They are called implicitly or explicitly by the child constructor. The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if we want a constructor that will accept an int , we have to define it explicitly
CM505.39 60 Advantages of Inheritance When one class is inherited from another class the code that provides a behavior required in the derived class need not have to be rewritten that is code be reused which increases reliability.
CM505.39 61 Advantages of Inheritance Code sharing can occur at several levels. For example, At a higher level , many users can use the same class. At lower level, code can be shared by two or more classes.
CM505.39 62 Advantages of Inheritance When multiple classes inherit from the same base class, it guarantees that the behavior they inherit will be the same in all classes.
CM505.39 63 Advantages of Inheritance Inheritance permits the construction of reusable software components. Using inheritance one can concentrate on understanding the portion of the new system.
CM505.39 64 Advantages of Inheritance The development time in developing a system will be reduced rapidly.
Inheritance Inheritance can be continuous Derived class can inherit from a base class The derived class can act as a base class and another class can inherit from it If you change the base class, all derived classes also change Any changes in the derived class do not change the base class All features of the base class are available in the derived class However, the additional features in the derived class are not available in the base class CPS235:Inheritance 65
CPS235:Inheritance 66
CPS235:Inheritance 67 Inheritance a b C lass A Features: a,b c C lass B F eatures: a,b,c d e C lass C F eatures: a,b,d,e f C lass D F eatures: a,b,d,e,f
Inheritance and Encapsulation private member Is accessible only via the base class public member Is accessible everywhere (base class, derived class, othe classes) protected member Is accessible by the base class and derived classes
CPS235:Inheritance 69 Inheritance Concept Rectangle Triangle Polygon class Polygon { private: int width, length; public: void set(int w, int l); }; class Rectangle{ private: int width, length; public: void set(int w, int l); int area(); }; class Triangle{ private: int width, length; public: void set(int w, int l); int area(); };
CPS235:Inheritance 70 Rectangle Triangle Polygon class Polygon { protected: int width, length; public: void set(int w, int l); }; class Rectangle: public Polygon { public: int area(); }; class Rectangle{ protected: int width, length; public: void set(int w, int l); int area(); }; Inheritance Concept
CPS235:Inheritance 71 Rectangle Triangle Polygon class Polygon { protected: int width, length; public: void set(int w, int l); }; class Triangle : public Polygon { public: int area(); }; class Triangle{ protected: int width, length; public: void set(int w, int l); int area(); }; Inheritance Concept
CPS235:Inheritance 72 Inheritance Concept Point Circle 3D-Point class Point { protected: int x, y; public: void set(int a, int b); }; class Circle : public Point { private: double r; }; class 3D-Point: public Point { private: int z; }; x y x y r x y z
Declaring Inheritance Syntax: class DerivedClassName : access-level BaseClassName where access-level specifies the type of derivation private by default, or public or protected (used very rarely) CPS235:Inheritance 73
CPS235:Inheritance 74 Class Derivation Point 3D-Point class Point{ protected: int x, y; public: void set(int a, int b); }; class 3D-Point : public Point{ private: double z; … … }; class Sphere : public 3D-Point{ private: double r; … … }; Sphere Point is the base class of 3D-Point , while 3D-Point is the base class of Sphere
What to Inherit? In principle , every member of a base class is inherited by a derived class just with different access permission CPS235:Inheritance 75
CPS235:Inheritance 76 Access Control Over the Members Two levels of access control over class members class definition inheritance type class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … … };
Member Access Control There are 3 levels of member (data or methods) access control: public: members can be used by itself and the whole world; any function can access them protected: methods (and friends ) of itself and any derived class can use it private: members can only be used by its own methods ( and its friends ) We’ll study friend functions later Without inheritance, private and protected have the same meaning The only difference is that methods of a derived class can access protected members of a base class, but cannot access private members of a base class CPS235:Inheritance 77
Access Rights of Derived Classes The type of inheritance defines the minimum access level for the members of derived class that are inherited from the base class With public inheritance, the derived class follows the same access permission as in the base class With protected inheritance, only the public members inherited from the base class can be accessed in the derived class as protected members With private inheritance, none of the members of base class is accessible by the derived class private protected public private private private private protected private protected protected public private protected public Type of Inheritance Access Control for Members
Access Rights of Derived Classes Take these classes as examples: class B { /*...*/ }; class D_priv : private B { /*...*/ }; class D_prot : protected B { /*...*/ }; class D_publ : public B { /*...*/ }; class UserClass { B b ; /*...*/ }; None of the derived classes can access anything that is private in B In D_priv , the public and protected parts of B are private In D_prot , the public and protected parts of B are protected In D_publ , the public parts of B are public and the protected parts of B are protected ( D_publ is-a-kind-of-a B ) class UserClass can access only the public parts of B , which "seals off" UserClass from B CPS235:Inheritance 79
CPS235:Inheritance 80 protected vs. private So why not always use protected instead of private? Because protected means that we have less encapsulation All derived classes can access protected data members of the base class Assume that later you decided to change the implementation of the base class having the protected data members For example, we might want to represent address by a new class called Address instead of string If the address data member is private, we can easily make this change The class documentation does not need to be changed. If it is protected, we have to go through all derived classes and change them We also need to update the class documentation.
CPS235:Inheritance 81 Class Derivation Example mother daughter son class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; class daughter : public mother{ private: double a; public: void foo ( ); }; void daughter :: foo ( ){ x = y = 20; set(5, 10); cout<<“value of a ”<<a<<endl; z = 100; // error, a private member }; daughter can access 3 of the 4 inherited members
CPS235:Inheritance 82 Class Derivation Example mother daughter son class mother{ protected: int x, y; public: void set(int a, int b); private: int z; } class son : private mother{ private: double b; public: void foo ( ); } void son :: foo ( ){ x = y = 20; set(5, 10); cout<<“value of b ”<<b<<endl; z = 100; // error, not a public member } son can also access 3 of the 4 inherited members
CPS235:Inheritance 83 mother daughter son granddaughter grandson Class Derivation Example class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; class daughter : public mother{ private: double a; public: void foo ( ); }; class granddaughter : public daughter{ public: void foo ( ); };
CPS235:Inheritance 84 void granddaughter :: foo ( ){ x = y = 20; //OK set(5, 10); //OK cout<<“value of a ”<<a<<endl; //error: private member of daughter z = 100; // error, a private member of mother }; Class Derivation Example
CPS235:Inheritance 85 mother daughter son granddaughter grandson class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; class son : private mother{ private: double b; public: void foo ( ); }; class grandson : public son{ public: void foo ( ); }; Class Derivation Example
CPS235:Inheritance 86 void grandson:: foo ( ){ x = y = 20; //ERROR: not accessible set(5, 10); //ERROR: not accessible z = 100; // error, a private member of mother }; Class Derivation Example
Encapsulation class Figure { protected: int x, y; }; class Circle : public Figure { public: int radius; }; int main() { Circle a; a.x = 0; a.y = 0; a.radius = 10; }
Encapsulation class Figure { protected: int x_, y_; }; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { x_ = x; y_ = y; radius_ = radius; } int main() { Circle a(0,0,10); }
Encapsulation class Figure { private: int x_, y_; }; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { x_ = x; y_ = y; radius_ = radius; } int main() { Circle a(0,0,10); }
Encapsulation class Figure { private: int x_, y_; public: void SetX ( int x); void SetY ( int y); }; void Figure:: SetX ( int x) { x_ = x; } void Figure:: SetY ( int y) { y_ = y; } class Circle : public Figure { private: int radius_; public: Circle( int x, int y, int radius); }; Circle::Circle( int x, int y, int radius) { SetX (x); SetY (y); radius_ = radius; } int main() { Circle a(0,0,10); }
What to Inherit? In principle, every member of a base class is inherited by a derived class just with different access permission However, there are exceptions for Constructor and destructor Overloaded Assignment operator Friends Since all these functions are class-specific! CPS235:Inheritance 91
Constructor Rules for Derived Classes The default constructor and the destructor of the base class are always called when a new object of a derived class is created or destroyed CPS235:Inheritance 92 class A { public: A ( ) {cout<<“A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class B : public A { public: B (int a) {cout<<“B”<<endl;} }; B test(1); A:default B output:
Constructor Rules for Derived Classes You can also specify a constructor of the base class other than the default constructor DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) { DerivedClass constructor body } CPS235:Inheritance 93 class A { public: A ( ) {cout<<“A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class B : public A { public: B (int a):A(a) {cout<<“B”<<endl;} }; B test(1); A:parameter B output:
CPS235:Inheritance 94 What is the result? class Figure { public: Figure() { cout << "Figure Constructor\n"; } ~Figure() { cout << "Figure Destructor\n"; } }; class Circle : public Figure { public: Circle() { cout << "Circle Constructor\n"; } ~Circle() { cout << "Circle Destructor\n"; } }; int main() { Circle a; }
Constructor Rules for Derived Classes Base constructor is called before the derived class constructor Destructors vice versa CPS235:Inheritance 95
Calling the Base Class constructor class Figure { public: Figure() { cout << "Figure Constructor\n"; } ~Figure() { cout << "Figure Destructor\n"; } }; class Circle : public Figure { public: Circle() : Figure() { cout << "Circle Constructor\n"; } ~Circle() { cout << "Circle Destructor\n"; } }; int main() { Circle a; }
Calling the Base Class constructor class Figure { private: int x, y; public: Figure( int xVal , int yVal ):x( xVal ), y( yVal ) { cout << "Figure Constructor\n"; } ~Figure() { cout << "Figure Destructor\n"; } }; class Circle : public Figure { private: double radius; public: Circle(int xVal, int yVal, int r) : Figure(xVal, yVal), radius(r) { cout << "Circle Constructor\n"; } ~Circle() { cout << "Circle Destructor\n"; } }; int main() { Circle a(0,0,5); }
CPS235:Inheritance 98 Define its Own Members Point Circle class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ private: double r; public: void set_r(double c); }; x y x y r protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); The derived class can also define its own members, in addition to the members inherited from the base class
CPS235:Inheritance 99 Even more … A derived class can override methods defined in its parent class. With overriding, the method in the subclass has the identical signature to the method in the base class a subclass implements its own version of a base class method class A { protected: int x, y; public: void print () {cout<<“From A”<<endl;} }; class B : public A { public: void print () {cout<<“FromB”<<endl;} };
CPS235:Inheritance 100 class Point { protected: int x, y; public: void set(int a, int b) {x=a; y=b;} void foo (); void print(); }; class Circle : public Point{ private: double r; public: void set (int a, int b, double c) { Point :: set(a, b); //same name function call r = c; } void print(); }; Access a Method Circle C; C.set (10,10,100); // from class Circle C.foo (); // from base class Point C.print (); // from class Circle Point A; A.set (30,50); // from base class Point A.print (); // from base class Point
Public CPS235:Inheritance 101 Putting It All Together Time is the base class ExtTime is the derived class with public inheritance The derived class can inherit all members from the base class, except the constructor access all public and protected members of the base class define its private data member provide its own constructor define its public member functions override functions inherited from the base class ExtTime Time
CPS235:Inheritance 102 Time class example
CPS235:Inheritance 103 class Time class Time { public: Time () :hrs(0), mins (0), secs (0){} Time ( int h, int m, int s):hrs(h), mins (m), secs (s){} void Set ( int h, int m, int s ) {hrs = h;mins = m;secs =s;} void Increment ( ) { cout <<"Calling base class Increment"<< endl ;} void Write ( ) const { cout <<hrs<<":"<< mins <<":"<< secs ;} protected : int hrs ; int mins ; int secs ; } ;
CPS235:Inheritance 104 Class Interface Diagram Protected data: hrs mins secs Set Increment Write Time Time Time class
Derived Class ExtTime enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ; class ExtTime : public Time // Time is the base class and use public inheritance { public : void Set ( int h, int m, int s, ZoneType timeZone ) ; void Write ( ) const; //overridden ExtTime(int h, int m, int s,ZoneType z) ; ExtTime(); // default constructor private : ZoneType zone ; // added data member } ; CPS235:Inheritance 105
CPS235:Inheritance 106 Class Interface Diagram Protected data: hrs mins secs ExtTime class Set Increment Write Time Time Set Increment Write ExtTime ExtTime Private data: zone
CPS235:Inheritance 107 Implementation of ExtTime Default Constructor ExtTime :: ExtTime () { zone = EST ; } The default constructor of base class, Time(), is automatically called, when an ExtTime object is created ExtTime et1; hrs = 0 mins = 0 secs = 0 zone = EST et1
CPS235:Inheritance 108 Implementation of ExtTime Another Constructor ExtTime :: ExtTime ( int h, int m, int s, ZoneType z): Time (h, m, s),zone(z) {} ExtTime et2 (8,30,0,EST); hrs = 8 mins = 30 secs = 0 zone = EST et2
Derived Class ExtTime ExtTime :: ExtTime ():zone(EST){} ExtTime :: ExtTime (int h, int m, int s, ZoneType z) : Time (h, m, s),zone(z) {} void ExtTime :: Set(int h,int m,int s, ZoneType z) { Time :: Set (h, m, s); // calling same name function of the base class zone = z; } void ExtTime ::Write()const // function overriding { string zoneString[8] = {"EST", "CST", "MST", "PST", "EDT", "CDT", "MDT", "PDT"} ; Time :: Write ( ) ; // calling same name function of the base class cout <<' '<<zoneString[zone]<<endl; } CPS235:Inheritance 109
Using class ExtTime int main() { ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; thatTime.Write( ); // prints 00:00:00 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // prints 16:49:23 CDT thisTime.Increment ( ) ; //prints Calling Base Class Increment thisTime.Increment ( ) ; //prints Calling Base Class Increment thisTime.Write ( ) ; // prints 08:35:02 PST getch(); } CPS235:Inheritance 110
Multiple Inheritance #include <iostream> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class COutput { public: void output (int i); }; void COutput::output (int i) { cout << i << endl; } CPS235:Inheritance 111
Multiple Inheritance class CRectangle: public CPolygon, public COutput { public: int area () { return (width * height); } }; class CTriangle: public CPolygon, public COutput { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0; } CPS235:Inheritance 112
Ambiguities in Multiple Inheritance See code examples CPS235:Inheritance 113
Friend functions A friend function of a class is defined outside that class's scope, yet has the right to access the non-public (and public) members of the class Let’s say you want a function to operate on objects of two different classes and access their private data, you would need to use a friend function CPS235:Inheritance 114
Example of friend functions class beta; // req for frifunc declaration class alpha { private: int data; public: alpha():data(3) {} friend int frifunc (alpha, beta); //friend func declaration }; class beta { private: int data; public: beta():data(7) {} friend int frifunc ( alpha,beta ); //friend func declaration }; CPS235:Inheritance 115 A class cannot be referred to until it has been declared
Example of friend functions int frifunc (alpha a, beta b) //friend func defined { return ( a.data + b.data ); } void main() { alpha aa ; beta bb; cout << frifunc ( aa,bb )<< endl ; //friend func called getch (); } CPS235:Inheritance 116
friend classes The member functions of a class can all be made friends at the same time when you make the entire class a friend If class alpha declares class beta as a friend class, then all member functions of class beta can access private data of class alpha It is also possible to declare only one member function of another class to be a friend CPS235:Inheritance 117
friend classes class beta; class alpha { private: int data; public: alpha():data(3) {} friend class beta; //friend class declaration }; class beta { public: void func (alpha a) { cout <<"alpha's data: "<< a.data ; } }; CPS235:Inheritance 118
Class member functions as friends class CSquare; class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend void CRectangle::convert(CSquare); }; CPS235:Inheritance 120
Class member functions as friends void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); getch(); return 0; } CPS235:Inheritance 121
Summary (friends) Even though the prototypes for friend functions appear in the class definition, friends are not member functions Friend declarations can be placed anywhere in a class definition either in public, private or protected sections Violates the data hiding principle of classes, so it should be avoided as much as possible Friendship is granted, not taken i.e., for class B to be a friend of class A, class A must explicitly declare that class B is its friend The friendship relation is neither symmetric nor transitive CPS235:Inheritance 122
Exercise Consider a publishing company that markets both book and audio-cassette versions of its work Create a class “publication” that stores the title (a string) and price (type float) of a publication Create a class sales that holds an array of three floats so that it can record the sales of a particular publication for the last three months Derive two classes: “book”, which adds a page count (type int); and “tape”, which adds a playing time in minutes(type float) from both publication and sales. Each of these four classes should have a getdata() function to get its data from the user and putdata() function to display its data An object of class book or tape should input and output publication as well as sales data along with its own data Write a main() function to create a book object and a tape object and exercise their input/output capabilities CPS235:Inheritance 123
Compulsory Reading Deitel and Deitel (5 th edition) Topic: 10.3. Composition: Objects as Members of Classes Topic: 10.4. Friend functions and Friend classes Robert Lafore Chapter 9: Inheritance (complete) Chapter 11: Topic: Friend functions (starts on page 572 in the e-book) CPS235:Inheritance 124