Posts Tagged ‘polymorphism’

Polymorphism

Tuesday, February 2nd, 2010

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 ‘Circle’
poly.cpp:21: note:   because the following virtual functions are pure within ‘Circle’:
poly.cpp:11: note:      virtual void Shape::printName()

Because the Circle was not implementing what the parent class has defined as a pure virtual function.

In the code below I have placed some error values if you do not put “public” in the same places. These are typical errors that come from access to the objects internals that you are trying to access.

#include <iostream>
#include <string>
 
using namespace std;
 
class Shape 
{
  public:
      Shape(const string& conName) : name(conName) {}; 
      // create a virtual function so that it is implemented in the subclass
      virtual void printName() = 0;
 
  // protected, so it does not allow direct access, but subclasses can access it.
  protected:
      const string name;
};
 
// need to be "public Shape" otherwise
// error: ‘Shape’ is an inaccessible base of ‘Circle’
// it will not allow access to the Shape class.
class Circle : public Shape
{
  // you need to specify public for Cat to access Animal string name because that is protected
  public :
      Circle (const string& conName) : Shape(conName) {};
      void printName()
      {
	  cout << name << " class" << endl;
      }
};
 
class Rectangle: public Shape
{
  // you need to specify public for Dog to access Animal string name because that is protected
  // error: ‘Rectangle::Rectangle(const std::string&)’ is private
  public: 
      Rectangle(const string& conName) : Shape(conName) {};
      void printName()
      {
	  cout << name << " class" << endl;
      }
};
 
int main()
{
    Shape* shapes[2];
    shapes[0] = new Circle("Cirlce");
    shapes[1] = new Rectangle("Rectangle");
 
    for (int i =0; i < 2 ; i++)
    {
      shapes[i]->printName();
      // clean up the memory space.
      delete(shapes[i]);
    }
    return 0;
}

and here is the output

Cirlce class
Rectangle class

So in the example code above, the polymorphism is when for example the Rectangle class is defining the “interface” code for printName method.

Overrideing polymorphism – c#

Friday, January 15th, 2010

Overrideing is also similar to overloading (sometimes it can be called the same thing since you are overloading/polymorphism functions and classes).

Polymorphism is when you implement functions that are defined in the base class, overriding is when you over ride a base class function.

But with Overrideing classes in c# you can override functions from the base class that are declared as virtual. Virtual means that they are capable of being overridden in a inherited class, so that incase someone tries to call a method of a same name in a subclass then the base class is still called e.g. sometimes better using code and output to show more than what words can say.

Here is not using the virtual keyword in the base class, so that when you try to call the subclasses same method it still goes to the base class.

using System;
 
namespace polymorphism
{
	class Shape {
		public void printName()
		{
			Console.WriteLine("Shape base class");
		}
	}
 
	class Circle : Shape {
		public new void printName()
		{
			Console.WriteLine("Circle class");
		}
	}
 
	class Rectangle : Shape {
		public new void printName()
		{
			Console.WriteLine("Rectangle class");
		}
	}
 
	class Line : Shape {
		public new void printName()
		{
			Console.WriteLine("Line class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Shape[] shapesArray = new Shape[4];
			shapesArray[0] = new Shape();
			shapesArray[1] = new Circle();
			shapesArray[2] = new Rectangle();
			shapesArray[3] = new Line();
 
			foreach (Shape shape in shapesArray)
			{
				shape.printName();
			}
		}
	}
}

output would

Shape base class
Shape base class
Shape base class
Shape base class

but with the

virtual -  override

keywords.

The code

using System;
 
namespace polymorphism
{ 
	class Shape {
		public virtual void printName()
		{
			Console.WriteLine("Shape base class");
		}
	}
 
	class Circle : Shape {
		public override void printName()
		{
			Console.WriteLine("Circle class");
		}
	}
 
	class Rectangle : Shape {
		public override  void printName()
		{
			Console.WriteLine("Rectangle class");
		}
	}
 
	class Line : Shape {
		public override  void printName()
		{
			Console.WriteLine("Line class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Shape[] shapesArray = new Shape[4];
			shapesArray[0] = new Shape();
			shapesArray[1] = new Circle();
			shapesArray[2] = new Rectangle();
			shapesArray[3] = new Line();
 
			foreach (Shape shape in shapesArray)
			{
				shape.printName();
			}
		}
	}
}

As expected the printName() function was called from the subclasses, because of the virtual keyword.

Shape base class
Circle class
Rectangle class
Line class