3

There are two type of object initialisation using copy constructor:

Class object2(val1, val2); // <--- (1)

Same can be done by copying the contents of another class:

Class object1(val1, val2);
Class object2 = object1;  // <--- (2)

What is the difference between (1) and (2) ? Are they explicit calls and implicit calls or does it have to do with operator overloading?

jonsno
  • 279
  • 4
  • 17
  • 3
    (1) is explicit construction, not copy construction. (2) is copy assignment. Copy construction would be `Class object2( object1 );` If you don't overload the copy assignment operator, it will initialise the target object using the copy constructor. – paddy May 12 '16 at 07:17
  • 2
    1 ==> class constructor ; 2 ==> copy constructor; – Praveen May 12 '16 at 07:18
  • That mean that 2nd one copy constructor is being called. SO no overloading of = operator? – jonsno May 12 '16 at 07:20
  • 2
    @paddy 2 will never result in a call to the copy assignment operator. – user657267 May 12 '16 at 07:20

2 Answers2

2

Both constructs use constructors, but different constructors. First is a constructor taking two arguments, second is normally the copy constructor (can be defaulted). The explicit declarations should be like:

class Class {
    // constructor taking 2 args
    Class(int val1, const std::string& val2);
    // copy ctor
    Class(const Class& other);

    /* you could optionaly have a move ctor:
    Class(Class&& other); */
    ...
};
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

Here

1. case 1

Class object2(val1, val2);

will call the constructor with two arguments

Class(type a, type b);

2. case 2

Class object2 = object1;

will call the copy constructor

Class(const Class&);

Demo

Praveen
  • 8,945
  • 4
  • 31
  • 49