Copy Constructor
-
Hi I am having the following doubt regarding copy constructor E.g If I have class A then the copy constructor will be A(const A& x) { } why it can't be 1. A(const A x) { } 2. A(const A* x) { } Please give me the reason also
ragavan wrote:
1. A(const A x) { }
If the argument
x
is passed by value a copy is needed. This is the job of the copy constructor. Therefore we'd need to call the copy constructor to copy the argument to the copy constructor, and so on, endlessly recursively.ragavan wrote:
2. A(const A* x) { }
Because an object itself need copying, not the object indirected through a pointer. It could have worked this was but it doesn't make as much sense.
Steve
-
Hi I am having the following doubt regarding copy constructor E.g If I have class A then the copy constructor will be A(const A& x) { } why it can't be 1. A(const A x) { } 2. A(const A* x) { } Please give me the reason also
From the C++ Standard ISO/IEC 14882-1998 12.8/2: A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.
-
Hi I am having the following doubt regarding copy constructor E.g If I have class A then the copy constructor will be A(const A& x) { } why it can't be 1. A(const A x) { } 2. A(const A* x) { } Please give me the reason also
ragavan wrote:
Please give me the reason also
interview question ahha :)
"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
cheers, Alok Gupta VC Forum Q&A :- I/ IV Support CRY- Child Relief and You