Inheritance Saras M. Srivastava LEARN BY EXAMPLES PGT – Comp. Sc.

Slides:



Advertisements
Similar presentations
Chapter 5 Inheritance. Objectives Introduction, effects, and benefits of inheritance Base class and derived class objects Base class and derived class.
Advertisements

CLASS INHERITANCE Class inheritance is about inheriting/deriving properties from another class. When inheriting a class you are inheriting the attributes.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Need for Inheritance Capability of inheriting features. Transitive relationship. Reusablity of class.
Inheritance In C++  Inheritance is a mechanism for building class types from other class types defining new class types to be a –specialization –augmentation.
1 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept.
Inheritance and Composition (aka containment) Textbook Chapter –
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
You gotta be cool. Inheritance Base Classes and Derived Classes Inheritance: Public, Protected, Private What is inherited from the base class? Multiple.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
1 Another Way to Define A Class - Inheritance. 2 Inheritance Concept Rectangle Triangle Polygon class Polygon { private: int width, length; public: void.
1 Chapter 6 Object-Oriented Software Development.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב' Inheritence ( הורשה Inheritence ( הורשה ( השקפים מבוססים על שקפים של אליהו ברוטמן ומרינה.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
1 Chapter 14-1 Object- Oriented Software Development Dale/Weems.
1 Chapter 14-2 Object- Oriented Software Development Dale/Weems.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Chapter 4 Inheritance.
CMSC 202 Inheritance.
1 Chapter 14 Object-Oriented Software Development.
1 Chapter 14 Object- Oriented Software Development Dale/Weems.
1 Chapter 14 Object-Oriented Software Development Dale/Weems/Headington.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
1 Lecture OOP Course Inheritance Basics Shape.
1 Chapter 14 Object-Oriented Software Development Dale/Weems.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Inheritance.
INHERITANCE IN C++ Amit Saxena PGT(CS) KV Rangapahar Cantt. (Nagaland)
An Equal Opportunity University CS Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1 Link.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Inheritance - Multilevel MEENA RAWAT PGT (COMP) KV ONGC Chandkheda 1.
Abstract Classes and Interfaces 8. Building Applications Using C#/ Session 8 © Aptech Ltd. Objectives  Define and describe abstract classes  Explain.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Inheritance.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming Fundamentals1 Chapter 8 OBJECT MANIPULATION - INHERITANCE.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
10/18/2011ecs40 fall Software Development & Object- Oriented Programming ecs40 Fall 2012: Software Development & Object- Oriented Programming #02:
Chapter 2 Object-Oriented Design and C++ Dr. Youssef Harrath
1 Another way to define a class Inheritance..!!. 2 Why Inheritance ? Inheritance is a mechanism for building class types from existing class types defining.
1 Chapter 4: Another way to define a class Inheritance..!!
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
Object Oriented Programming  Programmer thinks about and defines the attributes and behavior of objects.  Often the objects are modeled after real- world.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance Concept Polygon Rectangle Triangle class Rectangle{
Inheritance CMSC 202, Version 4/02.
Polymorphism.
Inheritance and Run time Polymorphism
Review: Two Programming Paradigms
Polymorphism & Virtual Functions
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CS212: Object Oriented Analysis and Design
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Programming Techniques Course
COP 3330 Object-oriented Programming in C++
Chapter 14 Object-Oriented Software Development
Chapter 11 Inheritance and Polymorphism Part 1
Another way to define a class
Inheritance in C++ Inheritance Protected Section
Lecture 6: Polymorphism
Programming in C# CHAPTER 5 & 6
Computer Science II for Majors
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

Inheritance Saras M. Srivastava LEARN BY EXAMPLES 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( ); void display( ); };

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

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

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?

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

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

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

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?

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

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

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

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.

Example 4 class livingbeing { char specification[20]; int averageage; public: void read(); void show(); };

class ape : private livingbeing { int no_of_organs, no_of_bones; protected: int iq_level; public: void readape(); void showape(); };

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

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.

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

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

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

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?

Inheritance Concept Polygon class Rectangle : public Polygon{ public: class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Rectangle Triangle class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Rectangle : public Polygon{ public: float area(); };

Inheritance Concept Polygon class Triangle : public Polygon{ public: class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Rectangle Triangle class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Triangle : public Polygon{ public: float area(); };

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; };

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

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

Define a Class Hierarchy Syntax: class DerivedClassName : access-level BaseClassName 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

Class Derivation 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

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

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{ … … };

Access Rights of Derived Classes Type of Inheritance private protected public - Access Control for Members The type of inheritance defines the access level for the members of derived class that are inherited from the base class

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

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

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);

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);

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); };

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;} };

Access a Method class Point{ class Circle : public 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

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 Time ExtTime

class Time Specification // SPECIFICATION FILE ( time.h) class Time{ public : void Set ( int h, int m, int s ) ; void Increment ( ) ; void Write ( ) const ; Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default constructor protected : int hrs ; int mins ; int secs ; } ;

Class Interface Diagram Time class Set Protected data: hrs mins secs Increment Write Time Time

Derived Class ExtTime #include “time.h” // 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 } ;

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

Implementation of ExtTime Default Constructor ExtTime :: ExtTime ( ) { zone = EST ; } 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.

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); hrs = 8 mins = 30 secs = 0 zone = EST et2 5000 ??? 6000

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; }

Working with ExtTime #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.Write ( ) ; // outputs 08:35:02 PST }

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

QUESTIONS