Moule Lin
← All notes

In-Class Declaration and Definition

1. In-class definition

    What in-class definition means: the body (implementation) of a member function is written inside the class. C++ implicitly treats such functions as inline.

   A.h

class A
{
public:
A(void);
virtual ~A(void);
int test(){return 1;};
int test1();
};
As you can see, the member function test() of class A is defined inside the class, so it is implicitly inline. (Inlining trades space for time: at the cost of duplicating code, it only saves the overhead of the function call, thereby improving execution efficiency. If executing the code in the function body takes much longer than the call overhead, the gain is small. So inlining is not appropriate when the function body is long or contains loops, if or switch statements, or recursion.)

2. Out-of-class definition

   What out-of-class definition means: the member function is defined outside the class, like the member function test1() in class A, which only has a declaration inside the class.

   A.h

class A
{
public:
A(void);
virtual ~A(void);
int test(){return 1;};
int test1();
};
A.cpp

#include “A.h”

A::A(void)
{
}
A::~A(void)
{
}
int A::test1()
{
return 1;
}
This form of out-of-class definition uses separate files: the declaration and definition are in different files. The other form is same-file out-of-class definition, where the declaration and definition are in the same .cpp file.