Serenity Stack Holder
Serenity Stack Holder

Reputation: 297

Error C2662 issue

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.

Upvotes: 1

Views: 413

Answers (1)

In silico
In silico

Reputation: 52159

You have this:

Smetler* copy() const { return new Smetler* (*this); }    

This doesn't allocate a Smetler object. It allocates a pointer of type Smetler. You're attempting to convert a const Smetler& (which is the type of *this in const functions) to a Smetler*, which of course doesn't make a whole lot of sense.

What you probably want is this:

Smetler* copy() const { return new Smetler(*this); }

The above will allocate a new Smetler on the free store and copies the this object into the new space. You have to delete the 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 from copy(). In C++03, you can use std::auto_ptr (although it has been deprecated since it can accidentally be used in an unsafe situation e.g. you can't use auto_ptrs in containers like std::vector):

std::auto_ptr<Smetler> copy() const
{
    return std::auto_ptr<Smetler>(new Smetler(*this));
}

Or, if you can use C++11, use the much more superior std::unique_ptr which doesn't have any of auto_ptr's problems.

std::unique_ptr<Smetler> copy() const
{
    return std::unique_ptr<Smetler>(new Smetler(*this));
}

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!)

Upvotes: 5

Related Questions