2

Possible Duplicate:
Most vexing parse: why doesn't A a(()); work?
Difference between creating object with () or without

There is such code:

class MojaKlasa{
public:
  MojaKlasa(){}
  MojaKlasa(int i){}
  void fun(){}
};

int main()
{
  MojaKlasa a;
  a.fun();

  MojaKlasa b(1);
  b.fun();

  MojaKlasa c(); //  initialize with default constructor
  //c.fun(); error: request for member ‘fun’ in ‘c’, which is of non-class type ‘MojaKlasa()’

  return 0;
}
  • Why is there error for object c?
  • What is the way to make it work?
  • What does really mean MojaKlasa c() - is it function declaraton?
Community
  • 1
  • 1
scdmb
  • 15,091
  • 21
  • 85
  • 128

2 Answers2

4
MojaKlasa c();

This declares a function called c returning MojaKlasa, it's not an object declaration. If you want to declare a local object you need to omit the parentheses. It's just a language rule that the compiler has to interpret this form as a function declaration.

MojaKlasa c;
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
2
MojaKlasa c();

defines a function returning a MojaKlasa object.

MojaKlasa c;

defines an object c of type MojaKlasa.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69