C ++ inheritance error when placing an object on the stack

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?

+5
source share
2 answers

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.

+9
source

B b(); b, b. ? b Int "" f.

Int f();

, ?

, , :

B b;

operator new :

B* b = new B;
B* b = new B();
+4

All Articles