You are on page 1of 14

4/22/2011

INHERITANCE

The most powerful feature of Object-Oriented Programming. Inheritance is the process of creating new classes, called derived classes , from existing or base classes Derived class inherits all the capabilities of the base class but can add embellishments and refinements of its own. The base class is unchanged by this process. It permits code reusability Once a base class is written and debugged, it need not be touched again, but, using inheritance, can nevertheless be adapted to work in different situations. Reusing existing code saves time and money and increases a programs reliability. An important result of reusability is the ease of distributing class libraries.

INHERITANCE

W9L17

Department of Computer Science and Information Technology, University of Gujrat

INHERITANCE CONCEPT
INHERITANCE
Polygon
class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); 4 float area(); };

Rectangle

Triangle

class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); };

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

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

Rectangle

Triangle

Rectangle

Triangle

class Rectangle : public Polygon { public: float area(); };

class Triangle : public Polygon { public: float area(); };

4/22/2011

INHERITANCE CONCEPT
Point x y

DERIVED CLASS AND BASE CLASS


Circle x y r

3D-Point x y z

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


7

We can use inheritance to create a new class based on existing one , without modifying existing class. #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class Counter //base class { protected: //NOTE: not private unsigned int count; //count public: Counter() : count(0) //no-arg constructor { } Counter(int c) : count(c) //1-arg constructor { } unsigned int get_count() const //return count { return count; } Counter operator ++ () //incr count (prefix) { return Counter(++count); } };

DERIVED CLASS AND BASE CLASS


SPECIFYING THE DERIVED CLASS

class CountDn : public Counter //derived class { public: Counter operator -- () //decr count (prefix) { return Counter(--count); } }; //////////////////////////////////////////////////////////////// int main() { CountDn c1; //c1 of class CountDn cout << \nc1= << c1.get_count(); //display c1 ++c1; ++c1; ++c1; //increment c1, 3 times cout << \nc1= << c1.get_count(); //display it --c1; --c1; //decrement c1, twice cout << \nc1= << c1.get_count(); //display it cout << endl; return 0; }

DEFINE A CLASS HIERARCHY


Syntax:

CLASS DERIVATION
Point

class DerivedClassName : access-level


BaseClassName where access-level specifies the type of derivation
private by default, or public

3D-Point

Sphere

class Point{ protected: int x, y; public: void set (int a, int b); };

Any

class can serve as a base class

Thus a derived class can also be a base class


11

class 3D-Point : public class Sphere : public 3DPoint{ Point{ private: private: double z; double r; }; }; Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
12

4/22/2011

THE PROTECTED ACCESS SPECIFIER

ACCESS SPECIFIERS WITHOUT INHERITANCE.

We have increased the functionality of a class without modifying it. A new specifier : protected. What does this do? Class members (which can be data or functions) can always be accessed by functions within their own class, whether the members are private or public. But objects of a class defined outside the class can access class members only if the members are public.

THE PROTECTED ACCESS SPECIFIER

THE PROTECTED ACCESS SPECIFIER

Member functions can access members of the base class if the members are public, or if they are protected. They cant access private members. Protected member, on the other hand, can be accessed by member functions in its own class orand heres the keyin any class derived from its own class. It cant be accessed from functions outside these classes, such as main(). Inheritance doesnt work in reverse. The base class and its objects dont know anything about any classes derived from the base class.

WHAT TO INHERIT?

ACCESS CONTROL OVER THE MEMBERS

In principle, every member of a base class is inherited by a derived class


just with different access permission Keyword public specifies that objects of the derived class are able to access public member functions of the base class.

base class/ superclass/ parent class


members goes to

Two levels of access control over class members


The alternative is the keyword private When this keyword is used, objects of the derived class cannot access public member functions of the base class. Since objects can never access private or protected members of a class, the result is that no member of the base class is accessible to objects of the derived class.
17

derive from

class definition inheritance type


class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ };

derived class/ subclass/ child class

18

4/22/2011

ACCESS RIGHTS OF DERIVED CLASSES


Type of Inheritance

PUBLIC INHERITANCE
public protected public public base class (B) public members protected members private members
derived class (A) public protected inherited but not accessible class A : public B { // Class A now inherits the members of Class B // with no change in the access specifier for } // the inherited members

private protected public

private private private

protected protected protected

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

19

PROTECTED INHERITANCE
class A : protected B { // Class A now inherits the members of Class B // with public members promoted to protected } // but no other changes to the inherited members

PRIVATE INHERITANCE
class A : private B { // Class A now inherits the members of Class B // with public and protected members } // promoted to private

protected base class (B) public members protected members private members

derived class (A) protected protected inherited but not accessible

private base class (B) public members protected members private members

derived class (A) private private inherited but not accessible

ACCESS COMBINATIONS
#include <iostream> using namespace std; class A //base class { private: int privdataA; //(functions have the same access protected: //rules as the data shown here) int protdataA; public: int pubdataA; }; class B : public A //publicly-derived class { public: void funct() {int a; a = privdataA; //error: not accessible a = protdataA; //OK a = pubdataA; //OK }};

ACCESS COMBINATIONS(1)

class C : private A //privately-derived class { public: void funct() { int a; a = privdataA; //error: not accessible a = protdataA; //OK a = pubdataA; //OK }}; int main() { int a; B objB; a = objB.privdataA; //error: not accessible a = objB.protdataA; //error: not accessible a = objB.pubdataA; //OK (A public to B) C objC; a = objC.privdataA; //error: not accessible a = objC.protdataA; //error: not accessible a = objC.pubdataA; //error: not accessible (A private to C) return 0; }

4/22/2011

WHAT TO INHERIT?

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; } };
B test(1);
25

In principle, every member of a base class is inherited by a derived class

just with different access permission


class B : public A { public: B (int a) {cout<<B<<endl; } }; output: A:default
B
26

However, there are exceptions for


constructor and destructor operator=() member friends

Since all these functions are class-specific

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 }

DEFINE ITS OWN MEMBERS


The derived class can also define its own members, in addition to the members inherited from the base class
Point x y

class A { public: A() {cout<< A:default<<endl;} A (int a) {cout<<A:parameter<<endl;} };


C test(1);

class C : public A { public: C (int a) : A(a) {cout<<C<<endl;} };

class Point{ protected: int x, y; public: void set(int a, int b); };


class Circle{ protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); 28 };

x y Circle r

output: A:parameter
C
27

class Circle : public Point{ private: double r; public: void set_r(double c); };

EVEN MORE

Access a Method
class Point{ protected: int x, y; public: void set(int a, int b) {x=a; y=b;} If you not void foo (); provide body???? 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

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.

30

class A { protected: int x, y; public: void print () { cout<<From A<<endl;} };

class B : public A { public: void print () {cout<<From B<<endl;} };


29

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

4/22/2011

Access a Method
class Point{ protected: int x, y; public: void set(int a, int b) {x=a; y=b;} If you not void foo (); provide body???? 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

Putting Them Together


Time

Time is the base class ExtTime is the derived class with public inheritance The derived class can

31

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

ExtTime

Point A; A.set(30,50); // from base class


Point

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
32

A.print(); // from base class Point

CLASS

TIME SPECIFICATION
( time.h)

Class Interface Diagram


Time class
Set Increment Write Time Time
Protected data: hrs mins secs

// SPECIFICATION FILE

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

34

DERIVED CLASS EXTTIME


// SPECIFICATION FILE ( exttime.h)

Class Interface Diagram


ExtTime class

#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

Set Increment Write ExtTime ExtTime

Set Increment Write


mins Protected data: hrs

{ 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
35

Time Time

secs

Private data: zone

36

4/22/2011

IMPLEMENTATION OF EXTTIME
Default Constructor

IMPLEMENTATION OF EXTTIME
Another Constructor

ExtTime :: ExtTime ( ) { zone = EST ; }


The default constructor of base class, Time(), is automatically called, when an ExtTime object is created.

ExtTime et1;

et1 hrs = 0 mins = 0 secs = 0 zone = EST

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


et2 6000 5000 ???

5000 hrs = 8 mins = 30 secs = 0 zone = EST


38

37

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

WORKING WITH EXTTIME


#include exttime.h int main() { ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; constructor called thatTime.Write( ) ;

// default

void ExtTime :: Write ( ) const // function overriding { string zoneString[8] = {EST, CST, MST, PST, EDT, CDT, MDT, PDT} ; Time :: Write ( ) ; cout << <<zoneString[zone]<<endl; }
39

// outputs 00:00:00 EST

thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Increment ( ) ; thisTime.Write ( ) ; }
40

// outputs 08:35:02 PST

CLASS HIERARCHIES

CLASS HIERARCHIES

Inheritance has been used to add functionality to an existing class. Inheritance different purposes: Example models a database of employees of a widget company. Weve simplified the situation so that only three kinds of employees are represented. Managers manage, scientists perform research to develop better widgets, and laborers operate the dangerous widget-stamping presses.

The database stores a name and an employee identification number for all employees, No matter what category they are. However, for managers, it also stores their titles and golf club dues. For scientists it stores the number of scholarly articles they have published. Laborers need no additional data beyond their names and numbers.

4/22/2011

CLASS HIERARCHIES

CLASS HIERARCHIES

include <iostream> using namespace std; const int LEN = 80; //maximum length of names //////////////////////////////////////////////////////////////// class employee //employee class { private: char name[LEN]; //employee name unsigned long number; //employee number public: void getdata() { cout << \n Enter last name: ; cin >> name; cout << Enter number: ; cin >> number; } void putdata() const { cout << \n Name: << name; cout << \n Number: << number; } }; ////////////////////////////////////////////////////////////////

CLASS HIERARCHIES (1)


CLASS HIERARCHIES (2)


class manager : public employee //management class { private: char title[LEN]; //vice-president etc. double dues; //golf club dues public: void getdata() { employee::getdata(); cout << Enter title: ; cin >> title; cout << Enter golf club dues: ; cin >> dues; } void putdata() const { employee::putdata(); cout << \n Title: << title; cout << \n Golf club dues: << dues; } }

class scientist : public employee //scientist class { private: int pubs; //number of publications public: void getdata() { employee::getdata(); cout << Enter number of pubs: ; cin >> pubs; } void putdata() const { employee::putdata();

cout << \n Number of publications: << pubs; } }; //////////////////////////////////////////////////////////////// class laborer : public employee //laborer class { };

CLASS HIERARCHIES (3)


CLASS HIERARCHIES (OUTPUT)


int main() { manager m1, m2; scientist s1; laborer l1; cout << endl; //get data for several employees cout << \nEnter data for manager 1; m1.getdata(); cout << \nEnter data for manager 2; m2.getdata(); cout << \nEnter data for scientist 1; s1.getdata(); cout << \nEnter data for laborer 1; l1.getdata(); //display data for several employees cout << \nData on manager 1; m1.putdata(); cout << \nData on manager 2; m2.putdata(); cout << \nData on scientist 1; s1.putdata(); cout << \nData on laborer 1; l1.putdata(); cout << endl; return 0; }

Enter data for manager 1 Enter last name: Wainsworth Enter number: 10 Enter title: President Enter golf club dues: 1000000 Enter data on manager 2 Enter last name: Bradley Enter number: 124 Enter title: Vice-President Enter golf club dues: 500000 Enter data for scientist 1 Enter last name: Hauptman-Frenglish Enter number: 234234 Enter number of pubs: 999 Enter data for laborer 1 Enter last name: Jones Enter number: 6546544

4/22/2011

ABSTRACT BASE CLASS

LEVELS OF INHERITANCE
Classes can be derived from classes that are themselves derived. class A { }; class B : public A { }; class C : public B { };

We dont define any objects of the base class We use this as a general class. Whose sole purpose is to act as a base from which other classes are derived. Classes used only for deriving other classes are sometimes loosely called abstract classes. meaning that no actual instances (objects) of this class are created.

LEVELS OF INHERITANCE

LEVELS OF INHERITANCE

#include <iostream> using namespace std; const int LEN = 80; //maximum length of names //////////////////////////////////////////////////////////////// class employee { private: char name[LEN]; //employee name unsigned long number; //employee number public: void getdata() { cout << \n Enter last name: ; cin >> name; cout << Enter number: ; cin >> number; } void putdata() const { cout << \n Name: << name; cout << \n Number: << number; } };

LEVELS OF INHERITANCE(1)

LEVELS OF INHERITANCE(2)

class manager : public employee //manager class { private: char title[LEN]; //vice-president etc. double dues; //golf club dues public: void getdata() { employee::getdata(); cout << Enter title: ; cin >> title; cout << Enter golf club dues: ; cin >> dues; } void putdata() const { employee::putdata(); cout << \n Title: << title; cout << \n Golf club dues: << dues; } };

class scientist : public employee //scientist class { private: int pubs; //number of publications public: void getdata() { employee::getdata(); cout << Enter number of pubs: ; cin >> pubs; } void putdata() const { employee::putdata(); cout << \n Number of publications: << pubs; } }; //////////////////////////////////////////////////////////////// class laborer : public employee //laborer class { }; ////////////////////////////////////////////////////////////////

4/22/2011

LEVELS OF INHERITANCE(3)

class foreman : public laborer {

//foreman class

private: float quotas; //percent of quotas met successfully public: void getdata() { laborer::getdata(); cout << Enter quotas: ; cin >> quotas; } void putdata() const { laborer::putdata(); cout << \n Quotas: << quotas; }}; int main() {laborer l1; foreman f1; cout << endl; cout << \nEnter data for laborer 1; l1.getdata(); cout << \nEnter data for foreman 1; f1.getdata(); cout << endl; cout << \nData on laborer 1; l1.putdata(); cout << \nData on foreman 1; f1.putdata(); cout << endl; return 0;}

INHERITANCE
Multiple Inheritance

MULTIPLE INHERITANCE MULTIPLE INHERITANCE (CONTD.)

A class can be derived from more than one base class.

The

syntax for multiple inheritance is similar to that for single inheritance.


class Teacher { }; class Student { }; class Teach_asst: public Teacher, public Student

Base class

Teacher

Student

Base class

Teaching assistant

Derived class

The names of both the base classes are provided separated by a comma. The rules of inheritance and access for multiple inheritance are the same as for single inheritance.

CONSTRUCTORS
class Teacher{ private: int x; public: Teacher(){x =0;} Teacher(int s){x = s;} }; class Student{ private: int y; public: Student(){y = 0;} Student(int a){y = a;} };

CONSTRUCTORS (CONTD.)
class Teach_asst: public Teacher,public Student { private: int z; public: Teach_asst():Teacher(),Student() //constructor {z = 0;} Teach_asst(int s,int a,int b): Teacher(s),Student(a) {z = b;} };

//constructors

//constructor

10

4/22/2011

CONSTRUCTORS (CONTD.)
Constructors have to be defined to initialise the data members of all classes. The names of the base class constructor follow the colon and are separated by commas:

CONSTRUCTORS AND DESTRUCTORS


General

order for calling Constructors:

Teach_asst():Teacher(),Student();

If the constructors had arguments then:


Teach_asst(int s, arg for Teacher class int a, arg for Student class int b): arg for this class Teacher(s), call Teacher constructor Student(a) call Student constructor {z = b;} set own data member

Base classes as they appear in the list of base classes: Teacher, Student If there are member objects in the class, they are initialised next, in the order they appear in the derived class declaration. The object itself (using the code in its constructor).
General

order for calling Destructors:

The destructor of the class is called first, then those of member objects, and then the base classes.

AMBIGUITY IN MULTIPLE INHERITANCE

Two base classes have functions with the same name, while a class derived from both base classes has no function with this name. #include <iostream> using namespace std; class A {public: void show() { cout << Class A\n; }}; class B {public: void show() { cout << Class B\n; }}; class C : public A, public B {}; int main() { C objC; //object of class C // objC.show(); //ambiguous--will not compile objC.A::show(); //OK objC.B::show(); //OK return 0;}

AMBIGUITY (CONTD.)
It is upto the programmer to avoid such conflicts and ambiguities. Can be resolved by defining a new function display()in the derived class:

void Gamma::display() { Alpha::display(); Beta::display(); }

The compiler is able to detect the name clashes and resolves it.

RELATIONSHIPS BETWEEN CLASSES


INHERITANCE
Is-a relationship Relationship between a more general class (superclass) and a more specialized class (subclass) Every

We have learned about inheritance as a relationship between classes

There are 3 important relationships

Inheritance Aggregation Dependency

savings account is a bank account DVD rental is a rental

11

4/22/2011

AGGREGATION

EXAMPLE
is a Vehicle Inheritance Car has a set of Tires Aggregation
Car

Has-a relationship

Each Dog has a Paw (dog is not a generalization of paw!)

Objects of one class contain references to objects of another class

INCLUSION

IS-A RELATIONSHIPS
We

When we have a "has-a" relationship, we include the thing that the object has in the object definition as a data member
e.g. class Clock { int hour;

can also look at the "is-a" relationship

e.g. "a customer is a person "a minivan is an automobile a biplane is a plane


The

/* more goes here */ };

is-a relationship is distinctly different from the has-a relationship We can represent is-a relationships in object-oriented programming using by adding more to an object through inheritance

WHAT IS THE DIFFERENCE BETWEEN A "HAS A" AND "IS A" RELATIONSHIP??

AN "IS A" RELATIONSHIP DEALS WITH INHERITANCE.


class myClassA; class myClassB : public myClassA {}; In this example, myClassB "is a" myClassA obj as well as a myClassB object.

A "Has a" relationship deals with object data member in class myClassA; class myClassB { public: myClassA getA() { return myAObj; } private: myClassA myAObj; };

12

4/22/2011

INHERITANCE VS. COMPOSITION


Composition is generally used when you want the features of an existing class inside your new class, but not its interface Use inheritance for sub-typing, where you want your new type to have exactly the same interface as the existing type (plus any other member functions you want to add)

COMPOSITION (AGGREGATION)
Creating and using objects of other class within a different class Also known as embedded object (or sub-object)

EXAMPLE: COMPOSITION
class X { private: int m_Data; // data member public: X() {} // default constructor SetX (int k) // member function { m_Data = k; } }; class Y { private: int m_Data;

EXAMPLE: COMPOSITION (CONTD.)


public: X x; // composition Y() {} //default constructor }; void main() { Y y; // creating object of class Y y.x.SetX(20); // Access/sets the embedded object }

CONTAINERSHIP: CLASSES WITHIN CLASSES

CONTAINERSHIP: CLASSES WITHIN CLASSES

Another type of relationship, called a has a relationship, or containership We say that a starling has a tail, meaning that each starling includes an instance of a tail. In Object-Oriented Programming the has a relationship occurs when one object is contained in another. class A { }; class B { A objA; // define objA as an object of class A }; In some situations inheritance and containership relationships can serve similar purposes

13

4/22/2011

CONTAINERSHIP: CLASSES WITHIN CLASSES


class student {}; class employee {}; class manager { student stu; // stu is an object of class student employee emp; // emp is an object of class employee }; class scientist { student stu; // stu is an object of class student employee emp; // emp is an object of class employee }; class laborer { employee emp; // emp is an object of class employee };

14

You might also like