C ++ What to add to the class declaration and what not

I am completely confused where to put, for example. constructor definition. Sometimes you see something like this

// point.h
class Point {
  Point(int x, int y) {
    x_ = x;
    y_ = y;
  }
private:
  const int x_;
  const int y_;
}

Then you sometimes see something like this:

// point.h
class Point {
  Point(int x, int y);
private:
  const int x_;
  const int y_;
}

// point.cc
Point::Point(int x, int y) {
  x_ = x;
  y_ = y;
}

those. sometimes things like constructors, copy constructors, etc., are declared in .h, and then implemented in a file .cc, sometimes they are defined in the header, etc. But under what circumstances? Is this a good practice that isn't?

+3
source share
5 answers

Contrary to some answers, there are differences in the two practices.

If you put the implementation in a class declaration, the method will automatically be marked as inline. For very short methods like wrappers this is a very useful feature .

.cc, ( ) . , , , . , , , . :

// test.h
class A; // forward declaration of A
// #include "decl_of_class_A.h" // not needed here, because ...

class B {
public:
  A method1();        // in these cases the forward
  void method2(A* a); // declaration of A above 
  void method3(A& a); // is completely sufficient.
};

// test.cc
#include "decl_of_class_A.h" // here we really need
                             // the complete declaration of A
                             // in order to be able to *use* it

A B::method1() { /*...*/ }
// ...

, test.h .cc A , test.cc, .cc. B .

: , : , ​​ inline.

Omnifarious : , , ++. const . , . , , - , :

Point p(10, 20);
Point q(0, 0);
q = p; // no assignment operator provided ==> error!

, const Point p(10, 20).

+5

. ().

:)

+2

cpp.

( /), . , .

, , TheClassName:: ( ).

+1

,

  • ,
  • , , LTCG.

, , , .

+1

, - . .

, , . inline .

, inline. , , , .

, , . , , , . .

, :

class Point {
  Point(int x, int y) : x_(x), y_(y) { }
private:
  const int x_;
  const int y_;
};

, const. , . , const.

, , const . , , , -. , , , , .

, , .

+1

Source: https://habr.com/ru/post/1795581/


All Articles