Possible duplicate:Why is this an error when using an empty set of brackets to call a constructor without arguments?
I have a small code example:
#include <iostream> using namespace std; class A { public: void print() { cout << "Hello" << endl; } }; class B: public A { public: B() { cout << "Creating B" << endl;} }; int main() { B b(); b.print(); // error: request for member βprintβ in βbβ, which is of non-class type βB ()()β }
However, if I go to the below if it works,
B* b = new B(); b->print();
Why doesn't this work when I allocate an object on the stack?
Because it B b();declares a function with a name bthat returns b. Just use B b;and blame C ++ for having a complicated grammar that makes this construct complicated.
B b();
b
B b;
B b(); b, b. ? b Int "" f.
Int
f
Int f();
, ?
, , :
operator new :
operator new
B* b = new B; B* b = new B();