Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these object initialisations? [duplicate]

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?

like image 871
jonsno Avatar asked Oct 26 '25 12:10

jonsno


2 Answers

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); */
    ...
};
like image 72
Serge Ballesta Avatar answered Oct 28 '25 02:10

Serge Ballesta


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

like image 41
Praveen Avatar answered Oct 28 '25 01:10

Praveen