Thuan Trinh Thuan Trinh - 1 year ago 59
C++ Question

How does copy constructor work?

How does a copy constructor work in c++

Error 1 error C2064: term does not evaluate to a function taking 1 arguments c:\users\thuan\dropbox\homework\css 342\lab2\lab2\lab2\lab2.cpp 26

#include "intset.h"

int main() {
IntSet object1;
IntSet object2(9);

object1(object2); //error here

return 0;
IntSet::IntSet(int a, int b, int c, int d, int e)
int tempArray[] = {a, b, c, d, e};
size = determineHighest(tempArray) + 1;

arrayPtr = new bool[size]();

for (int i = 0; i < MAXINITIALSIZE; i++)
if (tempArray[i] == -1)
arrayPtr[tempArray[i]]= true;
//copy constructor
IntSet::IntSet(const IntSet &intsetObject)
size = intsetObject.size;

arrayPtr = new bool[size];

for (int i = 0; i < size; i++)
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];

Answer Source

After you declare

InSet object1;

the object named object1 exists (created via the default constructor). Copy constructor (just like a regular constructor) creates a new object. Since the object already exists, the expression object1(object2); cannot be a copy-constructor call. For that, you need to declare your variables like this:

InSet object2(9);
InSet object1(object2);

If you wanted to copy object2 to the already existing object1, you will need an assignment operator (InSet& InSet::operator=(const InSet& other);)

Note: The compiler error is telling you that the expression (object1(object2); is a function call expression: you will need to define the function call operator (void InSet::operator()(const InSet& obj)) to make it compile (the return type could be anything else, not just void, depending on your need.) If you define the function call operator, you turn your object into what is called a functor

The compiler error (term does not evaluate to a function taking 1 arguments) is correct, but misleading wrt. to your problem (but there is no way for the compiler to know you wanted to use the copy constructor, instead of a function call)

Note: On many compilers the expression

InSet object2(9);
InSet object1 = object2;

also results in a call to the copy constructor (instead of default-constructing the object and then calling assignment operator on it), if available -- this is a possible compiler optimization.

Note: The declarations InSet object1; and InSet object2(9); are invalid if the only (regular) constructor you have is the one you listed, unless you have default values for the (regular) constructor's parameters in the class definition (where the constructor is declared), which you did not include.