[try Beta version]
Not logged in

 
why we are not using call by value method in copy constructor for passing the object to get copied?

Feb 8, 2015 at 5:33am
class X{
X(const X& obj1){}
};

int main()
{
X obj1;
X obj2 = obj1;
}
//we are passing the object by reference.
//the obj1's data members can be changed if we pass through reference
//so we are using const keyword
//now why are we passing through reference actually?
//why cant with pass through value like this?
//X(obj1){}?
Feb 8, 2015 at 5:43am
closed account (D80DSL3A)
Because it would result in infinite recursion.
When passed by value a copy is made for use in the function.
What's used to make this copy?
Feb 8, 2015 at 1:24pm
understood. thanks for ur post..
before i check on for what invokes the copy from the function, i need to know why are we not using pointers to pass the object? if we use what are the problems occur over there?
ur help is needed..
Feb 8, 2015 at 2:03pm
1
2
3
4
int main () {
  X * obj1 = nullptr;
  X   obj2( obj1 ); // Hmmm
}

KISS: When copy constructor creates a copy of an existing object, it does not have to worry about non-existent objects and whatnot.
Feb 8, 2015 at 5:34pm
closed account (D80DSL3A)
Sorry. Didn't mean to be cryptic in my answer.
What's used to make this copy?
A: The copy constructor makes the copy for the copy constructor.

A copy ctor which takes a pointer argument is a bad idea for the reason given by keskiverto and probably for other reasons too.
I have verified that it works, however.
A( const A* pa ):x(pa->x) {}// seems to work just fine if a valid pointer is given.
Last edited on Feb 8, 2015 at 5:35pm
Feb 8, 2015 at 7:56pm
> A copy ctor which takes a pointer argument
is not a copy constructor

§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 (8.3.6). [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.
Topic archived. No new replies allowed.