Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 709
zdd Avatar asked Oct 02 '12 07:10

zdd


2 Answers

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.

like image 85
Luchian Grigore Avatar answered Nov 11 '22 12:11

Luchian Grigore


What is the Difference between two declarations?

A a(); 

Declares a function and not an object. It is one of the Most vexing parse in C++.
It declares a function by the name a which takes no parameters and returns a type A.

A a;

Creates a object named a of the type A by calling its default constructor.

Why do you get the compilation error?

For a class default access specifier is private so You get the error because your class constructor is private and it cannot be called while creating the object with above syntax.

like image 32
Alok Save Avatar answered Nov 11 '22 14:11

Alok Save