Jay23 wrote: |
---|
Do i need copy constructor or is there a better solution? |
Define a copy-constructor only if your class contains dynamically allocated memory or if it inherits from another class. Otherwise, there's no need to overload it. For example:
1 2 3 4 5 6 7 8 9 10 11 12
|
struct Object_A
{
Object_A(void) : A(0), B(false) { }
int A;
bool B;
};
struct Object_B
{
Object_B(void) : Memory(new int(0)) { }
int *Memory;
};
|
In
Object_A, there's no need for a copy constructor because the compiler can handle those types with member-wise copies. However,
Object_B does require a copy constructor because of the memory allocated by
Object_B::Memory.
Note that the use of the assignment operator (
Object.operator = (...)) invokes the copy constructor. Also note that a copy-constructor requires a constant reference to the same type, with no other parameters. Finally, note that the compiler will only provide a copy constructor if your object requires it. For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// Code A
class Object;
int main(void)
{
::Object X, Y;
return(0);
}
// Code B
class Object;
int main(void)
{
::Object X, Y(X);
return(0);
}
|
Here, in
Code A, the compiler will not generate a copy constructor because it didn't need it. However, in
Code B, the compiler will generate a copy constructor because
Y used
X to initialise itself.
Wazzak