What are the differences between test t; and test t () ;? if Test is a class

Possible duplicate:
Why is there no constructor call?

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 between the two methods?

method 1

 Test t; 

way 2

 Test t(); 

I got this question in the code below, initially, I defined an instance of A in path 2, I have only one error, because B does not provide a default constructor, but when I define it in order 1, I got an additional 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 so that 1

 A a; 

I get another error:

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

Therefore, I suggest that there should be some differences between the two methods.

+7
source share
2 answers

enter image description here

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

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

+50
source

What is the difference between the two ads?

 A a(); 

Declares a function, not an object. This is one of the most annoying parsing in C ++.
It declares a function called a , which takes no parameters and returns a type a .

 A a; 

Creates an object named a type a , invoking its default constructor.

Why are you getting a compilation error?

For the default access specifier of the private class, thatโ€™s why you get an error because your class constructor is private and cannot be called when creating an object with the above syntax.

+17
source

All Articles