Jatin
Jatin

Reputation: 1987

Copy constructor with 2 argument

    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:

  1. How I can make a call to copy constructor having 2 arguments?
  2. When we require a copy constructor with 1 argument and when we require C.C with 2 argument?

Upvotes: 1

Views: 874

Answers (3)

cybevnm
cybevnm

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

Jerry Coffin
Jerry Coffin

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

Karoly Horvath
Karoly Horvath

Reputation: 96266

A constructor with 2 (or more) required arguments is not a copy constructor.

1.:

Sample s2(s1, 0);

Upvotes: 7

Related Questions