copy constructor not called during initialization

//Class.h
#include <iostream>
using namespace std;

class Class
{
public:
Class(int k)
{
cout << "cons" << endl;
};

Class(const Class& c)
{
cout << "copy-cons" << endl;
}
}

//main.cpp
#include "Class.h"

int main()
{
Class a(3); //cons
Class b = 3; //cons
Class c(a); //copy-cons
Class d = a; //copy-cons
return 0;
}

Note.Comments after a,b,c,d indicate the output

The question is, why it doesn't output copy-cons in the initialization of b? After all, it should call cons first on 3 to create a temp object and call copy-cons to construct b.

Is it due to specific task of the compiler? I use VS2008 currently.
After all, it should call cons first on 3 to create a temp object and call copy-cons to construct b.


It doesn't actually do that.

When you combine assignment with an object declaration, it calls the ctor instead of creating a temporary object. That's just one of the things of the language.

All of the below are different ways to do the exact same thing (no temp object created):

1
2
3
Class a(3);
Class b = 3;
Class c = Class(3);

Last edited on
Topic archived. No new replies allowed.