1 / 49

Inheritance

LEARN. Inheritance. BY EXAMPLES. Saras M. Srivastava PGT – Comp. Sc. Kendriya Vidyalaya Air Force Station Makarpura , Vadodara - 390014. Example1. class PUBLISHER { char pub[12]; double turnover; protected: void register( ); public: PUBLISHER( ); void enter( );

portia
Télécharger la présentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. LEARN Inheritance BY EXAMPLES Saras M. Srivastava PGT – Comp. Sc. Kendriya Vidyalaya Air Force Station Makarpura, Vadodara - 390014

  2. Example1 class PUBLISHER { char pub[12]; double turnover; protected: void register( ); public: PUBLISHER( ); void enter( ); void display( ); };

  3. class BRANCH { char city[20]; protected: float employees; public: BRANCH( ); void haveit( ); void giveit( ); };

  4. class AUTHOR: private BRANCH, public PUBLISHER { intacode; char aname[20]; float amount; public: AUTHOR( ); void start( ); void show( ); };

  5. Questions • Write the names of data members. Which are accessible from objects belonging to class AUTHOR. • Write the names of all the member functions which are accessible from objects belonging to class BRANCH. • Write the names of all the members which are accessible from member functions of class AUTHOR. • How many bytes will be required by an object belonging to class AUTHOR?

  6. Example 2 class Mydata { protected: int data; public: void Get_mydata(int); void Manip_mydata(int); void Show_mydata(int); Mydata( ); ~Mydata( ); };

  7. class Personal_data{ protected: int data1; public: void Get_personaldata(int); void Show_personaldata(int); Personal_data( ); ~Personal_data( ); };

  8. class Person: public Mydata, Personal_data{ public: void Show_person(void); Person( ); ~Person( ); };

  9. Questions • i) How many bytes will be required by an object belonging to class Person? • ii) Which type of inheritance is depicted in the above example? • iii) List the data members that can be accessed by the member function Show_person( ). • iv) What is the order of constructor execution at the time of creating an object of class Person?

  10. Example 3 class Goods { int id; protected : char name[20]; long qty; void Incr(int n); public : Goods(); ~Goods(); void get(); };

  11. class Food_products : public Goods { char exp_dt[10]; protected : int id; int qty; public : void getd(); void showd(); };

  12. class Cosmetics : private Goods { int qty; char exp_date[10]; protected : int id; public : ~Cosmetics(); Cosmetics(); void show(); };

  13. Questions (i) How many bytes will be required by an object of class Food_products. (ii) Name the member functions accessible through the object of class Food_products. (iii) From the following, Identify the member function(s) that cannot be called directly from the object of class Cosmetics show(), getd(), get() (iv) If the class cosmetics inherits the properties of food_products class also, then name the type of inheritance.

  14. Example 4 class livingbeing { char specification[20]; intaverageage; public: void read(); void show(); };

  15. class ape : private livingbeing { intno_of_organs, no_of_bones; protected: intiq_level; public: void readape(); void showape(); };

  16. class human : public ape { char race[20]; char habitation[30]; public: void readhuman(); void showhuman(); };

  17. Questions • Name the members which can be accessed from the member functions of class human. • Name the members, which can be accessed by an object of class human. • What will be the size of an object (in bytes) of class human. • Name the class(es) that can access read() declared in livingbeing class.

  18. Example 5 class vehicle { int wheels; protected: int passenger; public: void inputdata(); void outputdata(); };

  19. class heavyvehicle : protected vehicle { intdiesel_petrol; protected: int load; public: void readdata(int, int); void writedata(); };

  20. class bus : private heavyvehicle { char make[20]; public: void fetchdata(); void displaydata(); };

  21. Questions • Name the base class and derived class of heavyvehicle class. • Name the data member(s) that can be accessed from the function displaydata(). • How many bytes will be required by an object of vehicle and heavyvehicle classes respectively? • Is the member function outputdata() accessible to the objects of the class heavyvehicle?

  22. Inheritance Concept class Polygon{ protected: intnumVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, intnV); }; Polygon Rectangle Triangle class Rectangle{ protected: intnumVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, intnV); float area(); }; class Rectangle : public Polygon{ public: float area(); };

  23. Inheritance Concept class Polygon{ protected: intnumVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, intnV); }; Polygon Rectangle Triangle class Triangle{ protected: intnumVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, intnV); float area(); }; class Triangle : public Polygon{ public: float area(); };

  24. Inheritance Concept class Point{ protected: int x, y; public: void set (int a, int b); }; x y Point Circle 3D-Point x y r x y z class 3D-Point: public Point{ private: int z; }; class Circle : public Point{ private: double r; };

  25. Inheritance Concept • Augmenting the original class • Specializing the original class Polygon Point Rectangle Triangle Circle 3D-Point ComplexNumber RealNumber ImaginaryNumber

  26. Why Inheritance ? Inheritance is a mechanism for • building class types from existing class types • defining new class types to be a • specialization • augmentation of existing types

  27. Define a Class Hierarchy • Syntax: classDerivedClassName:access-levelBaseClassName where • access-level specifies the type of derivation • private by default, or • public • Any class can serve as a base class • Thus a derived class can also be a base class

  28. Class Derivation Point class Point{ protected: int x, y; public: void set (int a, int b); }; 3D-Point Sphere class 3D-Point : public Point{ private: double z; … … }; class Sphere : public 3D-Point{ private: double r; … … }; Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere

  29. What to inherit? • In principle, every member of a base class is inherited by a derived class • just with different access permission

  30. Two levels of access control over class members class definition inheritance type Access Control Over the Members class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … … };

  31. Access Rights of Derived Classes • The type of inheritance defines the access level for the members of derived classthat are inherited from the base class Type of Inheritance Access Control for Members

  32. Class Derivation class mother{ protected: intmProc; public: intmPubl; private: intmPriv; }; class grandDaughter : public daughter { private: double gPriv; public: void gFoo ( ); }; private/protected/public int main() { /*….*/ } class daughter : --------- mother{ private: double dPriv; public: void mFoo ( ); }; class daughter : --------- mother{ private: double dPriv; public: void dFoo ( ); }; void daughter :: dFoo ( ){ mPriv = 10; //error mProc = 20; };

  33. 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 • friends Since all these functions are class-specific

  34. 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. 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;} }; output: A:default B B test(1);

  35. Constructor Rules for Derived Classes You can also specify an constructor of the base class other than the default constructor • DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) • { DerivedClass constructor body } class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class C : public A { public: C (int a) : A(a) {cout<<“C”<<endl;} }; output: A:parameter C C test(1);

  36. Define its Own Members class Point{ protected: int x, y; public: void set(int a, int b); }; The derived class can also define its own members, in addition to the members inherited from the base class x y Point class Circle{ protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); }; x y r Circle class Circle : public Point{ private: double r; public: void set_r(double c); };

  37. 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<<“From B”<<endl;} };

  38. Access a Method 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(); }; 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

  39. Time ExtTime Putting Them 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

  40. classTime Specification // SPECIFICATION FILE ( time.h) class Time{ public : void Set ( int h, int m, int s ) ; void Increment ( ) ; void Write ( ) const ; Time ( intinitH, intinitM, intinitS ) ; // constructor Time ( ) ; // default constructor protected : inthrs ; intmins ; intsecs ; } ;

  41. Class Interface Diagram Timeclass Set Protected data: hrs mins secs Increment Write Time Time

  42. Derived Class ExtTime // SPECIFICATION FILE ( exttime.h) #include “time.h” 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 initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor private : ZoneType zone ; // added data member } ;

  43. Class Interface Diagram ExtTimeclass Set Set Protected data: hrs mins secs Increment Increment Write Write ExtTime Time ExtTime Time Private data: zone

  44. Implementation of ExtTime ExtTime :: ExtTime ( ) { zone = EST ; } Default Constructor ExtTime et1; et1 hrs = 0 mins = 0 secs = 0 zone = EST The default constructor of base class, Time(), is automatically called, when an ExtTime object is created.

  45. 5000 hrs = 8 mins = 30 secs = 0 zone = EST et2 6000 ??? 5000 Implementation of ExtTime Another Constructor ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer { zone = initZone ; } ExtTime *et2 = new ExtTime(8,30,0,EST);

  46. Implementation of ExtTime void ExtTime :: Set (int h, int m, int s, ZoneType timeZone) { Time :: Set (hours, minutes, seconds); // same name function call zone = timeZone ; } void ExtTime :: Write ( ) const // function overriding { string zoneString[8] = {“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ; Time :: Write ( ) ; cout <<‘ ‘<<zoneString[zone]<<endl; }

  47. Working withExtTime #include “exttime.h” … … int main() { ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called thatTime.Write( ) ; // outputs 00:00:00 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST }

  48. Take Home Message • Inheritance is a mechanism for defining new class types to be a specialization or an augmentation of existing types. • In principle, every member of a base class is inherited by a derived class with different access permissions, except for the constructors

  49. QUESTIONS

More Related