In C++ can constructor and destructor be inline functions?


Question

VC++ makes functions which are implemented within the class declaration inline functions.

If I declare a class Foo as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?

class Foo 
{
    int* p;
public:
    Foo() { p = new char[0x00100000]; }
    ~Foo() { delete [] p; }
};

{
    Foo f;
    (f);
}
1
67
8/21/2008 10:13:28 PM

Accepted Answer

Defining the body of the constructor INSIDE the class has the same effect of placing the function OUTSIDE the class with the "inline" keyword.

In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.

64
8/21/2008 10:10:59 PM

The short answer is yes. Any function can be declared inline, and putting the function body in the class definition is one way of doing that. You could also have done:

class Foo 
{
    int* p;
public:
    Foo();
    ~Foo();
};

inline Foo::Foo() 
{ 
    p = new char[0x00100000]; 
}

inline Foo::~Foo()
{ 
    delete [] p; 
}

However, it's up to the compiler if it actually does inline the function. VC++ pretty much ignores your requests for inlining. It will only inline a function if it thinks it's a good idea. Recent versions of the compiler will also inline things that are in seperate .obj files and not declared inline (e.g. from code in different .cpp files) if you use link time code generation.

You could use the __forceinline keyword to tell the compiler that you really really mean it when you say "inline this function", but it's usally not worth it. In many cases, the compiler really does know best.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon