Reputation: 1987
class Sample
{
public:
Sample(){}
Sample(const Sample& obj){ cout<<"C.C. with 1 argument called"<<endl;}
Sample(const Sample& obj, int i){ cout<<"C.C. with 2 arguments called"<<endl;}
};
void main()
{
Sample s1;
Sample s2 = s1; // Here, C.C with 1 arg. called.
}
There are few questions:
- How I can make a call to copy constructor having 2 arguments?
- When we require a copy constructor with 1 argument and when we require C.C with 2 argument?
Upvotes: 1
Views: 874
Reputation: 2566
Just to add little formalism here. Standard has strict definition for "Copy constructor" term (12.8 ):
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.
Upvotes: 4
Reputation: 490148
A class will only really have one copy ctor, which can be invoked with only one argument. It can take two (or more) arguments, but only if it provides default values for the other arguments. Either way, the first argument must be a (normally const) reference to an object of the same type.
Your second ctor taking two arguments isn't really a copy ctor (at least as the term is normally used) -- it's just a ctor that happens to take an instance as an argument (may base the new instance on that argument, at least in part).
Upvotes: 2
Reputation: 96266
A constructor with 2 (or more) required arguments is not a copy constructor.
1.:
Sample s2(s1, 0);
Upvotes: 7