Creating an instance of a class with ()

My question is: what constructor is used when instantiating a class c 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;
}

Thank!

+5
source share
2 answers

Tricky! You expect compilation to fail because the default constructor is private. However, it compiles and nothing is created. Cause?

Test instance_1();

... it's just a function declaration! (Which returns Testand accepts nothing.)

+11
source

Test instance_1(); , - instance_1, Test. , 0 , Test instance_1;.

+6

All Articles