I am trying to implement a prototype pattern.When I pass self object with *this
in order to clone itself with copy constructor I cannot access self member functions due to:
error: passing ‘const ConcreteClonable1’ as ‘this’ argument discards qualifiers [-fpermissive]
The error has to do with wrong usage of const
. However, if I remove const
from copy constructor everything works. I want to use copy constructor as it is supposed to, with const
argument, and the ability to access non-const class members.
Here is the code:
/* Prototype base class. */
class Prototype
{
protected:
std::string type;
int value;
public:
virtual Prototype* clone() = 0;
std::string getType() { return type; }
int getValue() { return value; }
};
//clonable class
class ConcreteClonable1 : public Prototype
{
public:
ConcreteClonable1(int number)
{
std::cout << "ConcreteClonable1 cnstr\n";
type = "Type1";
value = number;
}
//compilation error if const is used
ConcreteClonable1 (const ConcreteClonable1& x)
{
std::cout << "ConcreteClonable1 copy cnstr\n";
type = x.getType();
value = x.getValue();
}
Prototype* clone() { return new ConcreteClonable1(*this); }
};
The objects are initialized in a Factory
.
The question is why is this happening? Is there a better way to do this with some kind of copy function from c++ STL?