Difference between implementing a class inside a .h file or in a .cpp file

Viewed 34448

I was wondering which are the differences between declaring and implementing a class solely in a header file, compared with normal approach in which you protype class in the header and implement in effective .cpp file.

To explain better what I'm talking about I mean differences between normal approach:

// File class.h
class MyClass 
{
private:
  //attributes
  public:
  void method1(...);
  void method2(...);
  ...
};

//file class.cpp
#include "class.h"

void MyClass::method1(...) 
{
  //implementation
}

void MyClass::method2(...) 
{
  //implementation
}

and a just-header approach:

// File class.h
class MyClass 
{
private:
  //attributes
public:
  void method1(...) 
  {
      //implementation
  }

  void method2(...) 
  {
    //implementation
  }

  ...
};

I can get the main difference: in the second case the code is included in every other file that needs it generating more instances of the same implementations, so an implicit redundancy; while in the first case code is compiled by itself and then every call referred to object of MyClass are linked to the implementation in class.cpp.

But are there other differences? Is it more convenient to use an approach instead of another depending on the situation? I've also read somewhere that defining the body of a method directly into a header file is an implicit request to the compiler to inline that method, is it true?

6 Answers

Once in the past I created a module shielding from differences in various CORBA distributions and it was expected to work uniformly on various OS/compiler/CORBA lib combinations. Making it implemented in a header file made it more easy to add it to a project with a simple include. The same technique guaranteed that the code was recompiled at the same time when the code calling it required recompilation when i.e. it was being compiled with a different library or on a different OS.

So my point is that if you have a rather tiny library that is expected to be reusable and recompilable across various projects making it a header offers advantages in integration with some other projects as opposed to adding extra files to the main project or recompiling an external lib/obj file.

For me, the main difference is that a header file is like a "interface" for the class, telling clients of that class what are its public methods (the operations it supports), without the clients worrying about the specific implementation of those. In sense, its a way to encapsulate its clients from implementation changes, because only cpp file changes and hence the compilation time is much less.

Related