Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Inheritance.

Similar presentations


Presentation on theme: "Chapter 4 Inheritance."— Presentation transcript:

1 Chapter 4 Inheritance

2 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

3 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

4 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.

5 Inheritance Concept Polygon Rectangle Triangle class Rectangle{
private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Polygon Rectangle Triangle 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:

6 Inheritance Concept Polygon Rectangle Triangle
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(); };

7 Inheritance Concept Polygon Rectangle Triangle
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(); };

8 Figure 4.2 istringstream istream fstream ifstream IOS iostream
ostringstream ofstream

9 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

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

11 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.

12 Access Rules Public Inheritance Situation Public Protected Private
Base class member function accessing M Yes Derived class member function accessing M No Main, accessing B.M Main, accessing D.M Derived class member function accessing B.M 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.

13 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 members Derived() : Base() { }

14 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.

15 Example of partial method overriding
class Workaholic : public Worker { public: void doWork(){ // overriding base method Worker::doWork();// call base method drinkCoffee(); // new method Worker::doWork(); // call base method } };

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

17 Examples Worker *wptr; Worker w; cin>>x; Workaholic wh;
if(x != 0) wptr = new Workaholic(); else wptr = new Worker(); . . . //which doWork is used ? wptr -> doWork(); Figure 4.9 dynamic binding Worker w; Workaholic wh; . . . w.doWork(); wh.doWork(); figure 4.8 static binding

18 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:

19 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.

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

21 Example Which function is called?
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

22 Virtual Functions Definition: Example:
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{ virtual specifier needs to appear in the base class only.

23 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

24 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.

25 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.

26 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.

27 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.

28 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.

29 In this case the type of the pointer would be considered.
#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.

30 #include <iostream
#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.

31 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.

32 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

33 Figure 4.13 The abstract base class 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; };

34 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) //legal b= new Shape (“circle”) //illegal

35 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

36 class Base{ public: virtual void bar(); }; class Derived{ void bar(int x); Void test( Base & arg1, Derived & arg2){ arg1.bar(); // call Base::bar() => OK arg1.bar(4); //call Base::bar(int) => fails for not existing => OK arg2.bar(4); // call Derived::bar(int) => OK arg2.bar(); // fails b/c Derived::bar(int) has hidden Base::bar() } Get away by define one of the following two void bar(){Base::bar();} // in Derived class using Base::bar; // new std, may not be accepted by some compilers

37 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.

38 //: 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); } ///:~

39 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:

40 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.

41 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

42 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

43 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

44 Three Types of Inheritance
Access level of members will be changed by derivation. (private parts will always be invisible in derived class.) “public” inheritance Base Derived private (invisible) protected protected public public “private” inheritance protected private public private “protected” inheritance public 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

45 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.

46 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.

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


Download ppt "Chapter 4 Inheritance."

Similar presentations


Ads by Google