0

I'm having some doubts about this line:

Foo obj = Foo();

From what I know, here should be a constructor call for Foo() and then the copy constructor is called in order to initialize obj, but when I run this, the output shows that only the constructor is being called once. I know that the compiler does some optimizations on it's behalf, but I'm not sure whether this is one of them or maybe I'm just being wrong. The natural (without compiler optimization) call of constructors would be Constructor -> Copy Constructor and then Destructor(for temporary Foo() object)?

I'm not asking for practical use, but rather theoretical. I'm having an exam this days and I have to know the theoretical call of constructors, without optimizations.

  • Why call a copy constructor? – ForceBru Jun 09 '17 at 15:54
  • I know there are three cases when it's called: 1) When defining and initializing an object 2) When it's passed to a function by value 3) When an object is returned Doesn't it fit in the first case? Like the temporary Foo() object is created, then the copyconstructor would be called to initialize the obj object. – Alexandru Banu Jun 09 '17 at 15:57
  • The first case is wrong as you initialise an object with a 'normal' constructor (not copy or move one). A copy constructor returns a _copy_ of an object, right? And the returned object is _newly created_. If you used a copy constructor to craft new objects, that'd be an infinite loop and a waste of memory. – ForceBru Jun 09 '17 at 15:58
  • 1
    "and then the copy constructor is called in order to initialize obj". This line is incorrect. The line "Foo obj = Foo()" will never call the copy constructor. Copy constructor will be called in conditions when you are copying an object, for example: Foo obj2 = obj1; Other situations are: when you pass an object to a function by value and the function creates a local copy while receiving it. Copy constructor will also be called if you are returning an object from a function, something like: Foo func(){ //....stuff Foo temp; return temp; } – Sumit Jindal Jun 09 '17 at 16:01
  • @ForceBru `Foo obj = Foo();` Is *copy initialization* and the copy/move constructor is called if you tell the compiler not to elide constructors. It is also required that you have a valid copy or move constructor even if it is never called (until C++17). – NathanOliver Jun 09 '17 at 16:01
  • I found an answer in what NathanOliver marked as being a duplicate of, but thanks anyway. – Alexandru Banu Jun 09 '17 at 16:03

0 Answers0