I'm working through exercises in a book and have written the following class:
#ifndef BOX_H
#define BOX_H
#include <cstddef> // for std::size_t
class Box {
private:
double length {1.0},
width {1.0},
height {1.0};
inline static std::size_t object_count {};
public:
Box() = default;
Box(double length, double width, double height);
explicit Box(double side);
Box(const Box& box);
double volume() const;
bool has_larger_volume(const Box& other) const;
friend double surface_area(const Box& box);
double get_length() const { return this->length; };
double get_width() const { return this->width; };
double get_height() const { return this->height; };
void set_length(double length) { if (length > 0) this->length = length; };
void set_width(double width) { if (width > 0) this->width = width; };
void set_height(double height) { if (height > 0) this->height = height; };
static std::size_t get_object_count() { return Box::object_count; }
};
#endif
My question, specifically pertains to the use of the inline
keyword in this context. I understand that static member variables are created once at runtime regardless of the existence of class objects. object_count
would be defined multiple times, once for each translation unit and thus it is necessary to qualify it with inline
to allow this behavior.
But, why is it not necessary to qualify get_object_count()
with inline as well? Why doesn't that break ODR? Are all member functions implicitly inline regardless of being declared as static?