Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can implement the class's member function in header file?

Tags:

c++

linker

I know that you should only declare a function in header and avoid define it because if more than one source file include this header ,the linker will tell you there are duplicate symbol.

I also know that it is recommended that declare a class in header and implement the member function in source file

But here is my question : I try to define the whole class in header (including all the implementation of member function) ,then I found that there was no error from linker when I include this header in two source files.

Here is my header.h file

class ctr
{
public:
    ctr();
    ctr(char *s);
    int showname(){return 0;}
private:
    char *name;

};

In other two file, I include header.h

//file1.cpp
#include header.h

//file2.cpp
#include header.h

Then compile them g++ file1.cpp file2.cpp

So can anyone tell me why normal function definition will give me an error but class definition is ok?

like image 203
ctxrr Avatar asked Aug 30 '25 16:08

ctxrr


1 Answers

Member functions defined within the class body are implicitly inline [class.mfct]/p2:

A member function may be defined (8.4) in its class definition, in which case it is an inline member function [..]

The inline specifier allows a function to be defined across multiple translation units.

like image 151
David G Avatar answered Sep 02 '25 06:09

David G