Professional Documents
Culture Documents
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
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
4/22/2011
INHERITANCE CONCEPT
Point x y
Circle x y r
3D-Point x y z
class Point{ protected: int x, y; public: void set (int a, int b); };
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); } };
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; }
CLASS DERIVATION
Point
3D-Point
Sphere
class Point{ protected: int x, y; public: void set (int a, int b); };
Any
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
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.
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?
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
18
4/22/2011
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
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
private base class (B) public members protected members private members
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?
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
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
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
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
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
CLASS
TIME SPECIFICATION
( time.h)
// 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
#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
35
Time Time
secs
36
4/22/2011
IMPLEMENTATION OF EXTTIME
Default Constructor
IMPLEMENTATION OF EXTTIME
Another Constructor
ExtTime et1;
ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer { zone = initZone ; }
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 ; }
// 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
thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Increment ( ) ; thisTime.Write ( ) ; }
40
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 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 { };
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
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)
//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
The
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:
Teach_asst():Teacher(),Student();
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
The destructor of the class is called first, then those of member objects, and then the base classes.
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:
The compiler is able to detect the name clashes and resolves it.
INHERITANCE
Is-a relationship Relationship between a more general class (superclass) and a more specialized class (subclass) Every
11
4/22/2011
AGGREGATION
EXAMPLE
is a Vehicle Inheritance Car has a set of Tires Aggregation
Car
Has-a relationship
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;
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??
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
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;
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
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