1

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?

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • 1
    Part of your question is answered [here](https://stackoverflow.com/questions/46874055/why-is-inline-required-on-static-inline-variables). As for the member functions, when they are defined inside the class definition they are implicitly inline (no keyword required). – 1201ProgramAlarm Apr 16 '21 at 03:56
  • 1
    See the [top of this page](https://en.cppreference.com/w/cpp/language/inline). – super Apr 16 '21 at 04:26

0 Answers0