4

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?

2
  • 4
    because they are inlined Commented Jan 28, 2015 at 2:49
  • The problem is when things we know are not true. You can have inline functions in your header and C++ compiler + linker handle them just fine. A function with implementation inside the class is an inline function. Commented Feb 15, 2015 at 9:40

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.