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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With