Reputation: 177
According to One Definition Rule (ODR):
In the entire program, an object or non-inline function cannot have more than one definition; if an object or function is used, it must have exactly one definition.
These are my files that I am trying to compile:
A.cpp
#include <iostream>
#include "Greet.h"
int main()
{
greet();
std::cin.get();
}
B.cpp
#include "Greet.h"
Greet.h
#include <iostream>
void greet()
{
std::cout << "Hello World!" << std::endl;
}
I get a linker error as expected:
fatal error LNK1169: one or more multiply defined symbols found.
But when I put greet()
function in a class. The code compiles fine and gives the output Hello World!
.
A.cpp
#include <iostream>
#include "Greet.h"
int main()
{
Greet G;
G.greet();
std::cin.get();
}
B.cpp
#include "Greet.h"
Greet.h
#include <iostream>
class Greet
{
public:
void greet()
{
std::cout << "Hello World!" << std::endl;
}
};
Why is the linker not complaining about multiple definitions of class Greet
?
The behavior is the same for both MSVC and g++.
Upvotes: 4
Views: 354
Reputation: 206747
But when I put
greet()
function in a class. The code compiles fine and gives the outputHello World!
.
When a member function is defined inside a class definition, inline
is implied. That is not so for non-member functions.
From the C++ Standard, class.mfct:
A member function may be defined ([dcl.fct.def]) in its class definition, in which case it is an inline member function ([dcl.fct.spec]), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.
Upvotes: 6