7

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.

Community
  • 1
  • 1
zdd
  • 8,258
  • 8
  • 46
  • 75

2 Answers2

50

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.

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
17

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533