开发者

Creating an instance of a class with ()

开发者 https://www.devze.com 2023-03-22 01:01 出处:网络
I have a question : what constructor is used when you create an instance of a class with ClassName instance() in C++ ?

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
{
privat开发者_如何转开发e:
    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 !


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.)


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;.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号