i have two files, utility.h and utility.cpp. i declare a struct BoundingSphere in the .h file
struct BoundingSphere
{
BoundingSphere();
D3DXVECTOR3 _center;
float _radius;
};
BoundingSphere::BoundingSphere()
{
_radius = 0;
}
if i put the BoundingSphere::BoundingSphere() implementation into the .h file, i get a link error, error LNK2005: “public: __thiscall BoundingSphere::BoundingSphere(void)” already defined in bounding.obj
but, if i put the implementation into .cpp file, it works ok.
my question is that how it could happen?
This happens because your first code example breaks the One Definition Rule.
When you include the definition in the header file the precompiler merely copy pastes the content of the header in every translation unit where you include the header.
What you end up with is multiple definitions of the same function, this breaks the One Definition rule and hence the linker error.
If you need to add definitions in the header file then you need to mark the function as
inline. Though you should note that request toinlinea function is merely a suggestion to the compiler and it is free to accept or reject it.