rolam
rolam

Reputation: 1

C++ class definition

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?

Upvotes: 0

Views: 388

Answers (3)

ArBR
ArBR

Reputation: 4082

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; 
} 

Upvotes: 1

EboMike
EboMike

Reputation: 77732

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.

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89162

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.

Upvotes: 0

Related Questions