when we define a class member function in header file of that class then inline keyword must be used. why?

2.5k views Asked by At

i defined a class in header file and implemented its function in same header file. but while defining these functions i have to put inline keyword with function definition. Otherwise compiler gave compile time error.

I know inline is only a hint to compiler. So why it is necessary to put inline keyword with function definition.

I am using visual studio compiler with qt for compiling the code

here is the code

tempinline.h

#ifndef TEMPINLINE_H
#define TEMPINLINE_H
#include "iostream"
class tempinline
{
public:
    tempinline();
    void printH();
};
void tempinline::printH()
{
    std::cout << "hhhh";
}

#endif // TEMPINLINE_H

tempinline.cpp

#include "tempinline.h"

tempinline::tempinline()
{
}

main.cpp

#include <iostream>
#include "tempinline.h"

using namespace std;

int main()
{
    tempinline aa;
            aa.printH();
    cout << "Hello World!" << endl;
    return 0;
}

error

OUT:debug\tempinline.exe @C:\Users\utrade\AppData\Local\Temp\8\tempinline.exe.8256.687.jom
LINK : debug\tempinline.exe not found or not built by the last incremental link; performing full link
tempinline.obj : error LNK2005: "public: void __thiscall tempinline::printH(void)" (?printH@tempinline@@QAEXXZ) already defined in main.obj
debug\tempinline.exe : fatal error LNK1169: one or more multiply defined symbols found
jom: C:\Users\utrade\build-tempinline-Desktop-Debug\Makefile.Debug [debug\tempinline.exe] Error 1169
jom: C:\Users\utrade\build-tempinline-Desktop-Debug\Makefile [debug] Error 2
18:36:20: The process "C:\Qt\qtcreator-3.0.0\bin\jom.exe" exited with code 2.
Error while building/deploying project tempinline (kit: Desktop)
When executing step 'Make'
1

There are 1 answers

2
Himanshu Mahar On

after doing a lot of trying i am able to compile my code i comment the code in tempinline .cpp and also comment constructor timeinline(); declaration. So what was happening here is when i am including the header file more then once in a project then compiler see the multiple definitions of void tempinline::printH() function. so compiler was not able to know which function to linked and was giving linker error.

But if we specify inline keyword with function that is inline void tempinline::printH() then because of behavior of inline keyword, compiler do not have to link this function due to replacement(inline property) of code that is in the function to whereever it will be called