Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance error when object is allocated on the stack [duplicate]

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 ?

like image 966
Cemre Mengü Avatar asked Jul 10 '12 15:07

Cemre Mengü


1 Answers

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.

like image 109
Mark B Avatar answered Sep 30 '22 06:09

Mark B