C++ Interface – Organizing Interface and Implementation in C++

cheadersimplementations

I've seen that there are several different paradigms in C++ concerning what goes into the header file and what to the cpp file. AFAIK, most people, especially those from a C background, do:

foo.h

 class foo {
 private:
     int mem;
     int bar();
 public:
     foo();
     foo(const foo&);
     foo& operator=(foo);
     ~foo();
 }

foo.cpp

 #include foo.h
 foo::bar() { return mem; }
 foo::foo() { mem = 42; }
 foo::foo(const foo& f) { mem = f.mem; }
 foo::operator=(foo f) { mem = f.mem; }
 foo::~foo() {}
 int main(int argc, char *argv[]) { foo f; }

However, my lecturers usually teach C++ to beginners like this:

foo.h

 class foo {
 private:
     int mem;
     int bar() { return mem; }
 public:
     foo() { mem = 42; }
     foo(const foo& f) { mem = f.mem; }
     foo& operator=(foo f) { mem = f.mem; }
     ~foo() {}
 }

foo.cpp

 #include foo.h
 int main(int argc, char* argv[]) { foo f; }
 // other global helper functions, DLL exports, and whatnot

Originally coming from Java, I have also always stuck to this second way for several reasons, such as that I only have to change something in one place if the interface or method names change, that I like the different indentation of things in classes when I look at their implementation, and that I find names more readable as foo compared to foo::foo.

I want to collect pro's and con's for either way. Maybe there are even still other ways?

One disadvantage of my way is of course the need for occasional forward declarations.

Best Answer

While the second version is easier to write, it is mixing interface with implementation.

Source files which include header files need to be recompiled everytime the header files are changed. In the first version you'd change the header file only if you need to change the interface. In the second version you'd change the header file if you need to change the interface or the implementation.

Besides that you should not expose implementation details, you will get unneccessary recompilation with the second version.

Related Topic