Possible Duplicates:
Calling the default constuctor Why is it an error to use an empty set of brackets to call a constructor with no arguments?
I am wondering what it means to create an instance of a class using a no arguments constructor.
For example if I have a class "A" and try to create a variable like so:
A myVariable()
I tried to put together a little project to test it:
#include <iostream>
using namespace std;
class A
{
public:
A();
A( int a, int b );
public:
int mA;
int mB;
private:
virtual void init( int a , int b );
};
A::A()
{
cout << "\tA()" << endl;
this->init( 0, 0 );
} // end of function A::A
A::A( int a, int b = 0 )
{
cout << "\tA( int a, int b )" << endl;
this->init( a, b );
} // end of function A::A
void A::init( int a, int b )
{
cout << "\tInit( int a, int b )" << endl;
mA = a;
mB = b;
} // end of function A::init
int main()
{
cout << "Start" << endl;
cout << "A myA0()" << endl;
A myA0();
cout << "A myA1" << endl;
A myA1;
cout << "A myA2( 0 )" << endl;
A myA2( 0 );
cout << "A myA3( 0, 0 )" << endl;
A myA3( 0, 0 );
cout << "Stop" << endl;
return 0;
}
The output looks like this:
Start
A myA0()
A myA1
A()
Init( int a, int b )
A myA2( 0 )
A( int a, int b )
Init( int a, int b )
A myA3( 0, 0 )
A( int a, int b )
Init( int a, int b )
Stop
So it doesn't seem to call any constructor. When I try to step thro开发者_如何学Gough it in Visual Studio it just skips over it like it wasn't compiled and when I try to print out the variable i get an unknown extern symbol error.
Note: Of course when using the new operator doing "new A()" is required and will use the default constructor.
The syntax:
A myA0();
Does not create a variable of type A
by calling the default constructor, but rather declares a function taking no arguments and returning A
by value. Lookup in the tags for most-vexing-parse or something similar. To create a local variable just do:
A myA0; // no ()!!!
A different issue that you have to be aware is that a virtual method called from the constructor, or destructor will not use dynamic dispatch. The call to init
inside the A
constructor is a call to A::init
even if you are constructing an object of type B
derived from A
:
struct B : A {
void init( int, int ) { std::cout << "B::init(int,int)" << std::endl; }
};
int main() {
B b; // will print "\tInit( int a, int b )" from the constructor of `A`
b.init(); // will print "B::init(int,int)"
}
精彩评论