1
votes

What is the error in this file? I get:

foo2.cpp:9: error: expected primary-expression before '(' token
foo2.cpp:9: error: expected primary-expression before 'int'
foo2.cpp:9: error: expected ';' before '{' token
int main(void)
{
  class X {
    int i;
  public:
    X(int ii = 0);
  };

  X::X(int ii) { i = ii; }
  return 0;
}
2
I'm no C++ expert, so maybe this is some feature I've never head about, but I think you have to move the class and method outside of main(). - Ry-♦
@minitech the class is ok, it's method that's the problem. - Luchian Grigore
@LuchianGrigore: But if you move the method out of main() the class has to follow, right? - Ry-♦
@minitech if you move the method definition outside main, you also have to move the class definition outside, yes. - Luchian Grigore
Generally you would include your classes in a separate .h file and .cpp file for the methods. But I think Luchian Grigore solved your problem :) - silent

2 Answers

7
votes

First, may I ask, WHY?

Second, you can't provide an implementation inside a method (including main). If you must do this, keep the implementation inline:

int main()
{
  class X {
    int i;
  public:
    X(int ii = 0){ i = ii; }
  };
  return 0;
}
1
votes

You cannot nest functions in C++. To modify your program, you have two alternatives. You may move your class definition outside of main, or you may put your method definition inside the class:

First alternative:

class X {
  int i;
public:
  X(int ii = 0);
};

X::X(int ii) { i = ii; }

int main(void)
{
  return 0;
}

Second alternative:

int main(void)
{
  class X {
    int i;
  public:
    X(int ii = 0) { i = ii; }
  };

  return 0;
}