Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Basic Class Layout

Tags:

c++

class

Learning C++ and see the class laid out like this:

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

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

I know Java and methods(functions) in Java are written within the class. The class looks like a Java interface. I know I can write the class like this:

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

But is there a difference or standard?

like image 692
Spencer Avatar asked Dec 01 '22 10:12

Spencer


2 Answers

There's a difference. When you write the definition of the function within the class definition (case 2), then the function is considered to have been declared inline. This is standard C++.

Usage, is to declare the member functions (Java methods) within the class definition, in a header file (.h), and to define these member functions in a C++ file (.cpp, .cc, or .C, …) This reduces compilation time, when you change the body of a function, only the C++ file has to be compiled, whereas if you change something in the header file, all C++ files that include this header are to be compiled.

like image 60
Didier Trosset Avatar answered Dec 16 '22 03:12

Didier Trosset


It's much cleaner if you only define prototypes in the class definition (which belongs into a header file) and implement the methods in a cpp file.

When you have very small classes doing everything in the class definition might sound easier since everything is at the same place, but as soon as your class grows any developer using it will hate you since he'll have your code between the method prototypes he might look at to find out something (not everyone uses an IDE which shows all available methods!).

However, there is one exception: Template class methods needs to be implemented in the header as they need to be compiled for every specialization of the template.

like image 45
ThiefMaster Avatar answered Dec 16 '22 02:12

ThiefMaster