0

I have trouble understanding output of following code.

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
public:
    A() { cout << "A()" << endl; }
    ~A() { cout << "~A()" << endl; }
};

class B : public A
{
public:
    B() { cout << "B()" << endl; }
    ~B() { cout << "~B()" << endl; }
};

class C : public B
{
public:
    C() { cout << "C()" << endl; }
    ~C() { cout << "~C()" << endl; }
};

class D : public C
{
public:
    D() { cout << "D()" << endl; }
    ~D() { cout << "~D()" << endl; }
};

const B& returnConstB(B& b) { return b; }

B returnB(B b) { return b; }

A returnA(A a) { return a; }

int main() 
{
    D d;

    returnA(returnB(returnB(returnConstB(d))));

    cin.get();
    return 0;
}

At first, I have A,B,C,D constructors called when instantiating object d. After calling these couple of functions, the output is following:

~B()
~A()
~B()
~A()
~A()
~A()
~A()
~B()
~A()
~B()
~A()

I understand that there are copy constructors involved while passing a parameter by value and returning the value, but I can't quite understand when and where are these objects being created and destroyed in this case. Thanks in advance!

Pyranth
  • 135
  • 1
  • 5
  • It looks like you need to read a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), that explains _passing by value_, and _object slicing_ concepts. Since both `returnB`, and `returnA` takes its argument by value, and returns a copy of such object, they are both copied on function entry, and on `return` (even though `return` one _might_ be optimized away because of RVO). In addition to that, your objects are sliced, when entering such functions, so you end up with `B` (or `A) instance instead of `D`, that you passed in. – Algirdas Preidžius May 12 '17 at 21:23
  • A debugger is very handy in figuring this sort of stuff out. You put a breakpoint inside the destructors, run the program, and inspect the backtrace to see how you got to the destructor. – user4581301 May 12 '17 at 21:27

0 Answers0