I am doing some program, and so far so good when it’s about implementation, however now I am stuck with trivial problem, but I am in no position to find a solution for it. The problem is in this part of the code, and it say
Error 1 error C2662: ‘Smetler::action’ : cannot convert ‘this’ pointer from ‘const Smetler’ to ‘Smetler &’
Anyone knows what’s the problem here is, since I am sure I applied all what it was been said.
virtual void action()
{
std::cout << "I'm a copy" << copy() << ". Doing observations." << std::endl;
}
Smetler* copy() const { return new Smetler (*this); }
private:
void writeDown(ostream& wd) const
{
wd << Worker::getOccupation() << " " << Worker::getName() << ',' << Worker::getPosition() << action();
}
};
Thanks in advance.
You have this:This doesn’t allocate a
Smetlerobject. It allocates a pointer of typeSmetler. You’re attempting to convert aconst Smetler&(which is the type of*thisinconstfunctions) to aSmetler*, which of course doesn’t make a whole lot of sense.What you probably want is this:
The above will allocate a new
Smetleron the free store and copies thethisobject into the new space. You have todeletethe returned pointer eventually to avoid memory leaks.What you really want is to use a smart pointer so you won’t have to worry about
delete-ing the returned pointer fromcopy(). In C++03, you can usestd::auto_ptr(although it has been deprecated since it can accidentally be used in an unsafe situation e.g. you can’t useauto_ptrs in containers likestd::vector):Or, if you can use C++11, use the much more superior
std::unique_ptrwhich doesn’t have any ofauto_ptr‘s problems.Both the above code snippets will help a long way with preventing memory leaks (and not having to worry about them in the first place!)