0

I have a program below, and I'm trying to understand the following:

Why we don't enter the copy constructor when we have the temp' object C(...) that is the parameter for c1. I would also like to know how to identify this cases i.e when do we use the copy constructor and when not.

The program is:

#include<iostream>
using namespace std;

template <class T>
class A
{

public:

    T* t;

    A(T& obj) :t(&obj)
    {
        cout << "A::ctor" << endl;
    }
};

class B
{

public:

    int x1;

    B(int x) :x1(x)
    {
        cout << "B::ctor" << endl;
    }
};

class C
{

public:

    A<B> a;

    C(B& b) : a(b)
    {
        cout << "C::ctor" << endl;
    }

    C(const C& otherC) : a(otherC.a)
    {
        cout << "C::copy-ctor" << endl;
    }
};

int main(void)
{

    C c1(   C(  B(30)  )   );

    /*
    //The way i see it, which is wrong
    //Of course in this way b and c should be deleted 
    //some how (magically..) before using c1
    B b(30);
    C c(b);
    C c1(c);
    */

    return 0;
}
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
YigalO
  • 1
  • 1
  • 2
    You might want to read about [*copy elision*](https://en.wikipedia.org/wiki/Copy_elision). – Some programmer dude Sep 20 '15 at 12:49
  • πάντα ῥεῖ, can you please post the link! Joachim Pileborg, this topic appears in the book but frankly i don't understand it yet..i am reading the link you gave right now hoping it will solve my problem. – YigalO Sep 20 '15 at 13:05
  • http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization – YigalO Sep 20 '15 at 13:14

0 Answers0