Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can you inline a constructor?

Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile .

What kind of functions should not be inline?

We should not use functions that are I/O bound as inline functions. When large code is used in some function, then we should avoid the inline. When recursion is used, inline function may not work properly.

How are constructors and destructors executed?

The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object.

Does C has inline function?

The inline function can be substituted at the place where the function call is happening. Function substitution is always compiler choice. In an inline function, a function call is replaced by the actual program code.


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.


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.


Putting the function definition in the class body equivelent to marking a function with the inline keyword. That means the function may or may not be inlined by the compiler. So I guess the best answer would be "maybe"?


To the same extent that we can make any other function inline, yes.


To inline or not is mostly decided by your compiler. Inline in the code only hints to the compiler.
One rule that you can count on is that virtual functions will never be inlined. If your base class has virtual constructor/destructor yours will probably never be inlined.