Search code examples
c++most-vexing-parse

What's the differences between Test t; and Test t();? if Test is a class


Possible Duplicate:
Why is there no call to the constructor?

I am using Visual studio 2012, Suppose Test is a class

class Test
{
};

When I create a new instance of Test, what's the difference of the following two ways?

way 1

Test t;

way 2

Test t();

I got this question in the code below, originally, I defined an instance of A in way 2, I got only one error because B does not provide an default constructor, but when I define it in way 1, I got an extra error.

class B
{
    B(int i){}
};

class A
{
    A(){}
    B b;
};

int main(void) 
{ 
    A a(); // define object a in way 2

    getchar() ; 
    return 0 ; 
} 

if I define a in way 1

A a;

I will got another error said

error C2248: 'A::A' : cannot access private member declared in class 'A'

So I guess there must be some differences between the two ways.


Solution

  • enter image description here

    Test t; defines a variable called t of type Test.

    Test t(); declares a function called t that takes no parameters and returns a Test.