It's not just constructors. it's the same with normal member functions. Writing the function definition outside the class definition has has the advantage that you can split the code in an header (.h) and a source file (.cpp). This has many advantages like shorter compilation time and easier to handle circular dependencies (two classes that uses each other).
Lets me give you an example of 2 classes that use each other...
If you had all the code in the header file, including the implementation for that class then any classes that are used by said class have to be included into that header. For example...
Automobile.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include "Vehicle.h"
//also this nonsense class...
class Automobile
{
public:
//constructor that takes the Vehicle class as parameter.
Automobile(const Vehicle &vehicle) : m_vehicleType(vehicle.GetType){
}
private:
int m_vehicleType;
}
Since the Automobile class implements the usage of class Vehicle it has to include it. Which creates a dependency on the Vehicle class, anytime the header for Vehicle changes, Automobile also has to be recompiled. Instead of coupling the implementation in the header, suppose we implement in our cpp file. If we do that now we can just forward declare the Vehicle class, decoupling that dependency and avoiding dependent compilations.
e.g.
Automobile.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//Forward declaration... no dependency...
class Vehicle; //Defined in Vehicle.h
//also this nonsense class...
class Automobile
{
public:
//constructor...
Automobile(const Vehicle &vehicle);
private:
int m_vehicleType;
}
Automobile.cpp
1 2 3 4 5 6 7 8 9
#include "Vehicle.h" //Now you include the header, no longer dependency between the headers
//....
Automobile::Automobile(const Vehicle &vehicle) : m_vehicleType(vehicle.GetType)
{
}
//....
Imagine that Vehicle.h/.cpp are implemented using this strategy as well and all the files in your solution. As projects scale, compile times can become serious issues as well as the dependencies between them. I hope this helps.
In addition, if the definition is given at the same time as the declaration, the compiler is implicitly in-line the function; not mention type-checking.