5

Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

I have small code sample:

#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 change to the one below, if it works,

B* b = new B();

b->print();

Why doesn't it work when I allocate the object on the stack ?

Community
  • 1
  • 1
Cemre Mengü
  • 16,738
  • 25
  • 102
  • 161

2 Answers2

9

Because B b(); declares a function named b that returns a B. Just use B b; and blame the fact that C++ has a complex grammar that makes this sort of construct tricky.

Mark B
  • 93,381
  • 10
  • 105
  • 184
4

B b(); declares a function named b that takes nothing and returns B. Surprising? Try to rename your class B as Int, and name your "object" f. Now it looks like

Int f();

looks more like a function, doesn't it?

To define a default-constructed object, you need:

B b;

In case of operator new, the default constructor can be called with or without parentheses:

B* b = new B;
B* b = new B();
Armen Tsirunyan
  • 125,569
  • 56
  • 315
  • 427