9
votes

I have a c++ class, let's say it's called c, and I want to use the implicit copy constructor in one of the methods, like this:

c c::do_something() {
  c copy = this; //I want implicit copy constructor here!
  copy.something_else(); 
  //........//
  return copy;
}

However, gcc returns this error:

error: invalid conversion from 'c* const' to 'long unsigned int'

(I have another constructor from long unsigned int present)

... as if the copy constructor didn't exist. What am I doing wrong?

3

3 Answers

25
votes

this is a pointer to an object so it should be

c copy = *this;
7
votes

Quite an aside, but it won't really fit in a comment and there seems to be some disagreement. Try this piece of code out to get an idea of when copy-constructors and assignment operators get called:

class A
{
public:
    A() { cout << "A::A()\n"; }
    A(const A &) { cout << "A::A(const A &)\n"; }
    void operator =(const A &) { cout << "A::operator=(const A &)\n"; }
};

int main()
{
    A a; // default constructor
    A copy = a; // copy constructor (and no assignment operator)
    A copy2(a); // copy constructor (and no assignment operator)
    a = copy; // assignment operator
    A function(); // declares a function return A
    A b = A(); // default constructor (but no assignment operator)
    A b2 = A(a); // copy constructor (but no assignment operator)
}
3
votes

Whoa whoa! Also, don't confuse the copy constructor and the copy assignment operator.

c copy (*this);

is the copy constructor;

c copy = *this;

is the copy assignment operator. Either will work, though the copy constructor is technically more efficient, though the copy assignment operator is often optimized to do the same thing.


Wow - I find myself corrected. Using the = operator in the same statement as the declaration of a variable does indeed call the copy constructor. You learn something new every day!