0
class Rectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void) {return (x*y);}
};

void Rectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

I have this class inside of function of another class its giving error: a function-definition is not allowed here before ‘{’ token could you say me why?

EboMike
  • 76,846
  • 14
  • 164
  • 167
rolam
  • 1

3 Answers3

1

You can't have a write a function definition inside another function in C++. If anything, you'll need to write the implementation inside your class declaration, like you did with the area function.

EboMike
  • 76,846
  • 14
  • 164
  • 167
1

You should separe your declaration (.h) from your implementation (.cpp). If you want to implement some function in your declaration file (nomally for simple functions) you should use the inline reserved word:

Rectangle.h
class Rectangle { 
    int x, y; 
  public: 
    void set_values (int,int); 
    inline int area (void) {return (x*y);} 
}; 

Rectangle.cpp
#include Rectangle.h

void Rectangle::set_values (int a, int b) { 
  x = a; 
  y = b; 
} 
ArBR
  • 4,032
  • 2
  • 23
  • 29
  • I believe your use of "inline" is redundant here; member functions defined within the class body are implicitly inline. – Dan Nov 28 '10 at 04:20
  • @Dan:For simple functions like the one mentioned here, inline is the prefered style because of performance. See this question about this matter: http://stackoverflow.com/questions/145838/benefits-of-inline-functions-in-c – ArBR Nov 28 '10 at 04:28
0

You can make a type in function scope, but you can't declare the function there. You can do this:

class Rectangle { 
   int x, y; 
    public: 
      void set_values (int a, int b) { x = a; y = b; }
      int area (void) { return (x*y); } 
};

But, why not just declare Rectangle normally? It seems useful enough to want to use in other functions.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192