Docsity

C++ Inheritance & Virtual Functions: Pure, Simple, Non-Virtual, Exams of Object Oriented Programming

Partial preview of the text

Download C++ Inheritance & Virtual Functions: Pure, Simple, Non-Virtual and more Exams Object Oriented Programming in PDF only on Docsity!

Virtual functions and

Inheritance

Virtual functions

• Pure virtual functions

• Simple virtual functions

class Shape { public: virtual void draw() const = 0; virtual void error(const string &msg); … .. } class Rectangle: public Shape { …. };

Non-virtual functions

• The purpose of a non-virtual

function is to have derived

classes inherit a function

interface as well as a

mandatory implementation

C++ Tip

• Never redefine an inherited

non-virtual function

  • violates “is-a” inheritance rule
  • can lead to programming errors class B { public: void mf(); }; class D: public B { …. };

D x; // x is an object of type D B *pB = &x; // pB is pointer to x pB->mf(); // call mf through pointer D *pD = &x; // pD is pointer to x pD->mf(); // call mf through pointer