Reputation: 3316
Following code do not violate One Definition Rule, yet it is giving an unexpected result:
Test.hpp
class Test
{
public:
int test();
};
Test1.cpp
#include "Test.hpp"
int Test::test()
{
return 1;
}
int test1() // expected to return 1
{
Test a = Test();
return a.test();
}
Test2.cpp
#include "Test.hpp"
inline int Test::test() // doesn't violate ODR
{
return 99;
}
int test2() // expected to return 99
{
Test a = Test();
return a.test();
}
main.cpp
#include <iostream>
int test1();
int test2();
int main()
{
std::cout << test1() << std::endl;
std::cout << test2() << std::endl;
}
I am expecting it to print "1 99", but it always prints "1 1".
Regarding two definitions of Test::test, since one of them is an inline definition, it does not violate One Definition Rule as well.
So this program is valid, but it is not printing out expected result...
Is there anything wrong with this program? Or am I misunderstanding something about ODR rule? (a reference to C++ standard would be helpful).
Upvotes: 0
Views: 224
Reputation: 119219
You are not allowed to define the function as both inline
and non-inline
.
If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required.
([dcl.fct.spec]/4)
Upvotes: 3