Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it considered bad form in C++ to put a class declaration containing method definitions in a header file?

I am used to C, where header files usually only contain declarations and not definitions, but C++ seems to encourage the mixing of both, at least with classes. Take this class declaration which could easily be put in a header file. Some of its methods are defined inline, not in the sense of the "inline" keyword, but inline as in within the class declaration itself. Specifically the constructor and four getters/setters.

MyClass.h:

    class MyClass {
        public:
            MyClass(int a = 0, int b = 1) : _a(a), _b(b)  {};
            int getA() { return _a; };
            int getB() { return _b; };
            void setA(int a) { _a = a; };
            void setB(int b) { _b = b; };
            void doSomething(); // no definition here; defined in source file
            void doSomething2(); // no definition here; defined in source file
            void doSomething3(); // no definition here; defined in source file
        private:
            int _a;
            int _b;
    };

Is this bad form and should I define the class's methods separately in a source file, leaving only method declarations in the class declaration, or is this perfectly acceptable?

like image 581
tim Avatar asked Jan 27 '26 02:01

tim


1 Answers

It may be bad form, depending on the "bigger picture" of the applications using the header. By putting implementation into the header you're requiring modifications to the header when that implementation changes... such modifications trigger/require client object recompilation with many build systems (e.g. make). By way of contrast, out-of-line changes may require relinking, and when shared libraries are used those libraries may be able to be replaced without any changes to the client apps. Consequently, when there's no particular reason to use inlining, low-level headers shared by many applications tend to prefer out of line implementation. This is particularly true when the implementation can be expected to need changes.

Another reason some people prefer separating implementation is to avoid confusing people reading the API as a form of documentation. When there's less to read it's generally clearer, although sometimes the implementation helps in understanding the functionality. But, programmers who see the implementation tend to think about the behavioural/performance implications and build client code that depends on that, even if the interface doesn't make as strict guarantees: this makes the client code fragile should the implementation change.

like image 74
Tony Delroy Avatar answered Jan 28 '26 17:01

Tony Delroy