chapter 4 inheritance. objective is-a relationships and the allowable changes for derived classes...

47
Chapter 4 Inheritance

Upload: winfred-hunt

Post on 11-Jan-2016

233 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Chapter 4Inheritance

Page 2: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Objective

IS-A relationships and the allowable changes for derived classes

The concept of polymorphism Public, private, and protected members and inheritance Static vs. dynamic binding Default constructor, copy constructor, and copy

assignment operator Abstract classes Tricky C++ stuff

Page 3: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

4.1 What is Inheritance?

Another mechanism for code reuse. A process of deriving classes from a base class

without disturbing the implementation of the base class.

Inheritance models the IS-A relationship. In a is-a relationship the derived class is a variation of the base class.

Ex: Vehicle is a class

Car is a Vehicle => Car derived from Vehicle

Page 4: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Inheritance Concept

A key feature of C++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its "parent's" members, plus its own.

For example, we are going to suppose that we want to declare a series of classes that describe polygons like our CRectangle, or like CTriangle.

They have certain common properties, such as both can be described by means of only two sides: height and base.

This could be represented in the world of classes with a class CPolygon from which we would derive the two other ones: CRectangle and CTriangle.

Page 5: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

class Rectangle{

private:

int numVertices;

float *xCoord, *yCoord;

public:

void set(float *x, float *y, int nV);

float area();

};

Inheritance Concept

Rectangle Triangle

Polygon

class Polygon{

private:

int numVertices;

float *xCoord, *yCoord;

public:

void set(float *x, float *y, int nV);

};

class Triangle{

private:

int numVertices;

float *xCoord, *yCoord;

public:

void set(float *x, float *y, int nV);

float area();};

Ref: http://www.cse.ohio-state.edu/~neelam/courses/45922/

Page 6: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Rectangle Triangle

Polygonclass Polygon{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

};

class Rectangle : public Polygon{

public:

float area();

};

class Rectangle{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

float area();};

Inheritance Concept

Page 7: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Rectangle Triangle

Polygonclass Polygon{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

};

class Triangle : public Polygon{

public:

float area();

};

class Triangle{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

float area();};

Inheritance Concept

Page 8: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Figure 4.2

IOS

istream

ostream

iostream

ifstream

istringstream

ostringstream

ofstream

fstream

stringstream

Page 9: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

4.2 Inheritance Basics

Public inheritance: all public members of the base class remain public in the derived class =>models is-a relationship =>mostly used.

Private inheritance: hidden all inherited members from the public => models has-a relationship.

Syntax:

class DerivedClassName : access-level BaseClassName

Page 10: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

General layout of public inheritance class Derived: public Base{

// any members that are not listed are inherited unchanged //except for constructor, destructor, copy constructor, and //operator =

public://constructors, and destructors if defaults are not good// Base members whose definitions are to change in Derived// Additional public member functions

private://Additional data members(generally private)// Additional private member functions// Base members that should be disabled in Derived

};

Page 11: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Inheritance

Derived class inherits all member functions from the base class. It may accept, disallow, or redefine them.

Derived class can define new functions. Derived class can access public and

protected members of the base class.

Page 12: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Access Rules

Public Inheritance Situation Public Protected Private

Base class member function accessing M

Yes Yes Yes

Derived class member function accessing M

Yes Yes No

Main, accessing B.M Yes No No

Main, accessing D.M Yes No No

Derived class member function accessing B.M

Yes No No

Note: B is an object of the base class; D is an object of the publicly derived class; M is member of the base class.

Page 13: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Constructor and Base class initialization Constructors should be defined for each derived

class. If there is no constructor in a derived class, a

default zero-parameter constructor will be generated which in turn calls the zero-parameter constructor in the base class to initialize the inherited membersDerived() : Base() { }

Page 14: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Overriding a method(member function) Overriding base class methods: Derived

class methods must have the same signature and compatible return types with the base class methods.

Partial overriding: overriding base class methods by adding more functionality.

Page 15: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Example of partial method overridingclass Workaholic : public Worker{

public: void doWork(){ // overriding base method

Worker::doWork();// call base methoddrinkCoffee(); // new methodWorker::doWork(); // call base method

}};

Page 16: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Bindings Static binding: the decision about which

function/type to use to resolve an overload is made at compile time.

Dynamic binding: the decision must be made at run time.

If a function is redefined in a derived class, it should be declared virtual in the base class.

Example:class Worker{

public:virtual void doWork();

};

Page 17: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Examples

Worker w;Workaholic wh;

. . . w.doWork();wh.doWork();

figure 4.8 static binding

Worker *wptr;cin>>x;if(x != 0)

wptr = new Workaholic();else

wptr = new Worker();. . .//which doWork is used ?wptr -> doWork();

Figure 4.9 dynamic binding

Page 18: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Polymorphism

Static and dynamic binding In most programming languages and in most cases the

variables are bound to a specific type at compile time Static binding

Dynamic binding The type of the variable can change at run time Using pointers to classes related by inheritance in C++ In C we can use unions to allow dynamic binding of arbitrary

types Dangerous in some cases

Ref: www.cs.uh.edu/~mirkovic/cosc1305/

Page 19: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Polymorphism

Polymorphism, many forms, using the same name for “many different things.”

Polymorphism is the ability of a reference variable to reference objects of several different types.

When operations are applied to the variable, the operation that is appropriate to the actual reference object is automatically selected.

Derived class is a new class which inherits all public & protected properties of a base class.

Derived class is type-compatible with its base class.

Page 20: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

C++ Polymorphism Definition:

Single name denotes objects of different classes related by inheritance Ability to manipulate derived objects using the interface defined in the base

class Example:

class Employee { public:

void CalcPay ();};

class SalariedEmployee :public Employee{ public:

void CalcPay ();};

Page 21: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Example

Employee *ep;

ep = new SalariedEmployee;

Ep->CalcPay();

Which function is called? The function in Employee is called

To avoid that we have to declare CalcPay() as a virtual function

Page 22: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Virtual Functions

Definition: Nonstatic member function prefaced by the virtual specifier. Compiler generates the code that will select the appropriate function at

runtime Example:

class Employee { public:

virtual void CalcPay ();};class SalariedEmployee :public Employee{ public:

virtual void CalcPay ();};

virtual specifier needs to appear in the base class only.

Page 23: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Examples

Employee *p0 = new Employee;

Employee *p1 = new SalariedEmployee;

p0->CalcPay(); // calls Employee::CalcPay()

p1->CalcPay(); // calls SalariedEmployee::CalcPay()

Any nonstatic member function except a constructor can be virtual Virtual functions can also be friends of other classes Some compilers require the class destructor to be virtual if a class

contains any virtual functions

Page 24: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

C++ Virtual Function  

C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes.

The whole function body can be replaced with a new set of implementation in the derived class.

Page 25: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Properties of Virtual Functions

The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved.

A non-virtual C++ member function is resolved during compile time or static binding. Virtual Functions are resolved during run-time or dynamic binding

Virtual functions are member functions of a class. Virtual functions are declared with the keyword virtual.

Virtual function takes a different functionality in the derived class.

Page 26: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

v - table

Whenever a program has a virtual function declared, a v-table is constructed for the class.

The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions.

Page 27: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Virtual

A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor.

Destructors should be virtual for base class => Let the computer know which one to call for deallocation.

Page 28: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

virtual destructor

A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in the proper order.

It is to be remembered that destructors are called in the reverse order of inheritance.

If a base class pointer points to a derived class object and we some time later use the delete operator to delete the object, then the derived class destructor is not called.

Page 29: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

#include <iostream.h>class base{   public:   ~base()  {

  }};

class derived : public base{   public:   ~derived()   {     }};

void main(){

   base *ptr = new derived();   // some code   delete ptr;}

• In this case the type of the pointer would be considered.

• Hence as the pointer is of type base, the base class destructor would be called but the derived class destructor would not be called at all.

• The result is memory leak.

• In order to avoid this, we have to make the destructor virtual in the base class.

Page 30: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

#include <iostream.h>class base{public:virtual ~base(){

}};

class derived : public base{   public:   ~derived()   {

   }

};

void main(){

   base *ptr = new derived();   // some code   delete ptr;}

• no memory leak here.

Page 31: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

General rules

Nonvirtual functions: Overloading is resolved at compile time.

Virtual functions: Overloading is resolved at run-time

Pure virtual functions Overloading is resolved at run-time.

Page 32: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Abstract

Abstract method: A pure virtual function, has no meaningful definition in the base class and must always be defined in derived classes.

Abstract class: a class containing any abstract method = > can NOT be instantiated and must be inherited.Example: shape class

Page 33: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Figure 4.13 The abstract base class shapeclass Shape { public: Shape( const string & shapeName = "" ) :

name( shapeName ) { } virtual ~Shape( ) { } virtual double area( ) const = 0; //abstract

method bool operator< ( const Shape & rhs ) const

{ return area( ) < rhs.area( ); } virtual void print( ostream & out = cout

const { out << name << " of area "<< area( );

} private:

string name; };

Page 34: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

4.3 Examples: Expanding the Shape class Provide new constructors Write definition for inherited pure virtual

functions. Shape.cpp Example: Shape *a, *b;a= new Circle (3, 0) //legalb= new Shape (“circle”) //illegal

Page 35: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

4.4 Tricky C++ Details

Changing the default value in a derived class is unsafe because doing so can create an inconsistency with virtual functions.

When a method is declared in a derived class, it hides all methods of the same name in the base class => get away by partial overriding or using “using” directive

Page 36: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

class Base{public:virtual void bar();

};class Derived{

public:void bar(int x);

};Void test( Base & arg1, Derived & arg2){

arg1.bar(); // call Base::bar() => OKarg1.bar(4); //call Base::bar(int) => fails for not existing => OKarg2.bar(4); // call Derived::bar(int) => OKarg2.bar(); // fails b/c Derived::bar(int) has hidden Base::bar()

}

Get away by define one of the following twovoid bar(){Base::bar();} // in Derived classusing Base::bar; // new std, may not be accepted by some compilers

Page 37: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Inheritance Cont . .

An inherited method can be overridden required that the new method must have exact signature and the return type must be the same or of a derived type from the base class.

Default inheritance is private. Try to avoid it. Friend functions of a base class are not friends

of the derived ones. Slicing: casting a derived class to its base will

surrender data defined in the derived class.

Page 38: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

//: C15:Slice.cpp// Object slicing#include <iostream>using namespace std;

class Base { int i;public: Base(int ii = 0) : i(ii) {} virtual int sum() const { return i; }};

class Derived : public Base { int j;public: Derived(int ii = 0, int jj = 0) : Base(ii), j(jj) {} int sum() const { return Base::sum() + j; }};

void call(Base b) { cout << "sum = " << b.sum() << endl;}

int main() { Base b(10); Derived d(10, 47); call(b); call(d);

} ///:~

Page 39: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Slicing

The function call( ) is passed an object of type Base by value . It then calls the virtual function sum( ) for the Base object.

Two things are happening in this program. First, call( ) accepts only a Base object, so all the code inside the function body will manipulate only members associated with Base.

Any calls to call( ) will cause an object the size of Base to be pushed on the stack and cleaned up after the call. This means that if an object of a class inherited from Base is passed to call( ), the compiler accepts it, but it copies only the Base portion of the object. It slices the derived portion off of the object, like this:

Page 40: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

4.5 Multiple Inheritance

A mechanism for deriving a class from several base classes.

Ex: Student and Employee are derived classes of UniversityPerson.

class Student: virtual public UniversityPerson(){. . . };class Employee:virtual public UniversityPerson(){…};class StudentEmployee : public Student,

public Employee{. . .}; Virtual inheritance prevents duplicate data members

inherited from base classes.

Page 41: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

What a derived class inherits Every data member defined in the parent class (although such

members may not always be accessible in the derived class!) Every ordinary member function of the parent class (although

such members may not always be accessible in the derived class!)

The same initial data layout as the base class

What a derived class doesn't inherit

The base class's constructors and destructor The base class's assignment operator The base class's friends

Page 42: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

What happens when a derived-class object is created and destroyed

1. Space is allocated (on the stack or the heap) for the full object (that is, enough space to store the data members¤¤ inherited from the base class plus the data members defined in the derived class itself)

2. The base class's constructor is called to initialize the data members inherited from the base class

3. The derived class's constructor is then called to initialize the data members¤¤ added in the derived class

4. The derived-class object is then usable 5. When the object is destroyed (goes out of scope or is deleted) the

derived class's destructor is called on the object first 6. Then the base class's destructor¤ is called on the object 7. Finally the allocated space for the full object is reclaimed

http://burks.bton.ac.uk/burks/language/cpp/cppfaq/privatei.htm

Page 43: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Common errors (page 151)

Inheritance is private by default. A common error is to omit the keyword public, which is needed to specify public inheritance.

Objects of abstract classes can NEVER be initiated.

More errors defined in page 151

Page 44: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Three Types of Inheritance

- “public” inheritanceBase Derivedprivate (invisible)protected protectedpublic public

- “private” inheritanceBase Derivedprivate (invisible)protected privatepublic private

- “protected” inheritanceBase Derivedprivate (invisible)protected protectedpublic protected

protected, public parts will be unchanged(struct’s default)

protected, public parts will be private(class’s default)

protected, public parts will be protected

Access level of memberswill be changed by derivation.(private parts will always be invisible in derived class.)

Page 45: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

In class exercises

When should a constructor be virtual? When should a destructor be virtual? Explain the rules when to use virtual and

non-virtual functions.

Page 46: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Summary

Inheritance: a powerful way for code reuse Virtual: Dynamic binding, binding at

execution time. Abstract: must be defined in derived

classes. Abstract classes can’t be instantiated.

Friendship is not inheritable.

Page 47: Chapter 4 Inheritance. Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected

Homework

Hw 2: 3.4, 4.5, due on next wed. Finish reading chapter 4 and preview

chapter 6