9

I have a question : what constructor is used when you create an instance of a class with ClassName instance() in C++ ?

Example:

#include <iostream>

using namespace std;

class Test
{
private:
    Test()
    {
        cout << "AAA" << endl;
    }

public:
    Test(string str)
    {
        cout << "String = " << str << endl;
    }
};

int main()
{
    Test instance_1(); // instance_1 is created... using which constructor ?
    Test instance_2("hello !"); // Ok

    return 0;
}

Thanks !

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Congelli501
  • 2,403
  • 2
  • 27
  • 28

2 Answers2

13

Tricky! You would expect compilation to fail as default constructor is private. However, it compiles and nothing is created. The reason?

Test instance_1();

... is just a function declaration! (Which returns Test and takes nothing.)

tomasz
  • 12,574
  • 4
  • 43
  • 54
  • 3
    That is what I was about to say, but you beat me to it. This is C++ most vexing parse (http://en.wikipedia.org/wiki/Most_vexing_parse). – David Hammen Jul 21 '11 at 00:48
  • most vexing parse is a very apt name! and questions under this tag http://stackoverflow.com/questions/tagged/most-vexing-parse are an excellent proof. – tomasz Jul 21 '11 at 22:55
7

The statement Test instance_1(); doesn't call a constructor at all, because it's not defining a variable - instead, it's declaring a function called instance_1 that returns an object of type Test. To create an instance using the 0-argument constructor, you'd use Test instance_1;.

Hugh
  • 8,872
  • 2
  • 37
  • 42