Polymorphism means that you are deriving from a base class to create a new class, and the polymorphism is when you derive from the base class and implement a interface (virtual function in c++ speak as such) functions.

In C++ a virtual function would be

virtual void printName() = 0;

the = 0 means to set the virtual function to point to nothing (pure virtual function).

You could put some code within {} and still call it a virtual function, but that is taking away from the interface idea. (Java,C# and PHP use the interface structures)

In the code below, I have a const string (constant string) and as we know a constant string cannot be altered so to define this string when the constructor is called you place the variable name after the constructor and set it up to the constant value, e.g..

class Shape
     const string name;
      // constructor
     Shape(const string& constructorName) : name(constructorName) {};

This will setup the constant string when the Shape class has been created on the heap (memory allocation).

To call a parent class, Shape in this instance, constructor you just do something very similar to the setting of the constant string, you place it after the constructor in the subclass and put the parent class that you want to call its constructor after the “:” as

class Rectangle 
      Rectangle(const string& constructorName) : Shape(constructorName) {}

you can place more code into the {} for the Rectangle constructor still, but the “Shape(constructorName) is calling the parent class “Shape” constructor.

If you do not define the virtual pure function within the derived class, when you try to compile the error would be something similar to

poly.cpp:46: error: cannot allocate an object of abstract type 

Leave a Reply

Your email address will not be published. Required fields are marked *