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

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){}?
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?
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..
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.
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
> 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.