In C++, if a copy constructor is not defined the compiler will do that for you. If one is defined, compiler would not. The compiler generated copy constructor can be trivial or non-trivial. In a trivial copy constructor it does a member-wise copy. That's it.
However, if there is a virtual function, the copy constructor is non-trivial. It cannot just to bit-wise copy.
So here is my program. There is nothing special. Just to make my point..
#include<iostream>
using namespace std;
class baseClass
{
public:
int var;
int* varPtr;
const float floatVar;
int &intRefVar;
baseClass(int value) : var(value), varPtr(&var), floatVar(value), intRefVar(var)
{
cout << "baseClass constructor" << endl;
}
baseClass(const baseClass& objToCopy) : var(objToCopy.var), varPtr(&var), floatVar(objToCopy.floatVar), intRefVar(var)
{
cout << "baseClass copy constructor" << endl;
}
virtual void func()
{
cout << "Just a virtual func." << endl;
}
};
class derivedClass : public baseClass
{
public:
derivedClass(int value) : baseClass(value)
{
cout << "derivedClass constructor" << endl;
}
derivedClass(const derivedClass& objToCopy) : baseClass(objToCopy)
{
cout << "derivedClass copy constructor" << endl;
}
virtual void func()
{
cout << "Just another virtual func." << endl;
}
};
int main(int argc, char** argv)
{
derivedClass derClassObj1(10);
derivedClass derClassObj2(derClassObj1);
return 0;
}
In this program,
- I have defined a copy constructor
- I have a virtual function so the copy constructor is non-trivial
Here are my questions:
- How does a non-trivial copy constructor differ from a trivial one due to the presence of a vptr?
- Why cannot the vptr be copied? If both objects of same type (same level in the inheritance), they both can point to the same vtable, can they not?
- Since I have defined my own copy constructor, does the compiler 'add' special instructions to my copy constructor to handle the virtualness?
Cheers.