Inheritance......cont

What is inherited from the base class?

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

Constructor and destructor

operator=() member

friends

Although the constructor and destructor of the base class are not inherited, the default constructor (i.e. constructor with no parameters) and the destructor of the base class are always called when a new object of a derived class is created or destroyed.

If the base class has no default constructor or you want that an overloaded constructor is called when a new derived object is created, you can specify it in each constructor definition of the derived class:

derived_class_name (parameters) : base_class_name (parameters) {}

Different Forms of Inheritance

1. Single Inheritance:- When a derived class inherits from one base class, it is known as single

inheritance.

2. Multiple Inheritance:- When a derived class inherits from multiple base class, it is known as

multiple inheritance

3. Hierarchical Inheritance:- When many derived classes inherit from a single base class, it is known

as hierarchical inheritance.

Multiple Inheritance

In C++ it is perfectly possible that a class inherits fields and methods from more than one class simply by separating the different base classes with commas in the declaration of the derived class. For example, if we had a specific class to print on screen (COutput) and we wanted that our classes CRectangle and CTriangle also inherit its members in addition to those of CPolygon we could write:

class CRectangle: public CPolygon, public COutput {

class CTriangle: public CPolygon, public COutput {

here is the complete example:

// multiple inheritance

#include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class COutput { public: void output (int i); }; void COutput::output (int i) { cout << i << endl; } class CRectangle: public CPolygon, public COutput { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon, public COutput { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0; }