Ways to organize interface and implementation in C++

Posted by Felix Dombek on Programmers See other posts from Programmers or by Felix Dombek
Published on 2011-02-17T10:25:18Z Indexed on 2011/02/17 15:33 UTC
Read the original article Hit count: 329

Filed under:
|
|

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, and 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.

© Programmers or respective owner

Related posts about c++

Related posts about implementations