My intention is to make an empty virtual function in the base class. Redefine that function in the derived classes such that they return the particular subclass's object.
createShapeObjects is the factory method here.
What is the proper implementation for factory method according to GOF book?
facto.h
#ifndef FACTO
#define FACTO
class PaintShapes
{
public:
virtual PaintShapes createShapeObjects(string arg) {};
};
class PaintTriangle : public PaintShapes
{
public:
PaintTriangle() {}
virtual PaintShapes createShapeObjects(string arg)
{
std::cout << "ddd";
if (arg == "triangle")
return new PaintTriangle;
}
};
class PaintRectangle : public PaintShapes
{
public:
PaintRectangle() {}
virtual PaintShapes createShapeObjects(string arg)
{
std::cout << "eee";
if (arg == "rectangle")
return new PaintRectangle;
}
};
/////
// My class which wants to paint a triangle:
/////
class MyClass
{
public:
PaintShapes obj;
void MyPaint()
{
obj.createShapeObjects("triangle");
}
};
#endif // FACTO
main.cpp
#include <iostream>
using namespace std;
#include "facto.h"
int main()
{
cout << "Hello World!" << endl;
MyClass obj;
obj.MyPaint();
return 0;
}
This gives the error:
error: could not convert '(operator new(4u), (<statement>, ((PaintTriangle*)<anonymous>)))' from 'PaintTriangle*' to 'PaintShapes'
return new PaintTriangle;
^