c++ – Defining 2 identical classes does not give an error

Question:

//Файл A.cpp
class A
{
public:
    int func( int i )
    {
        return i*i;
    }
};

//Файл Test.cpp
#include <iostream>
using namespace std;

class A
{
public:
    int func( int i )
    {
        return i*i*i;
    }
};

int main()
{
    A a;
    cout<<a.func(2)<<endl;
    system("pause");
}

The question is why is there no compile time error? After all, there are two class definitions with the name A. The program works – it outputs 8.

I will add a question. If you rewrite the "A.cpp" file like this:

class A
{
public:
    int func( int i );
};

int A::func( int i )
{
    return i*i;
}

That will be a mistake!

The situation is similar with functions. The code below will not work.

//A.cpp
int func( int i )
{
    return i*i;
}

//Test.cpp
#include <iostream>
using namespace std;

int func( int i )
{
    return i*i*i;
}


int main()
{
    cout<<func(2)<<endl;
    system("pause");
}

All this kind of confuses me.

Answer:

According to the language standard (ODR rule), classes with external linkage (external linkage) defined in several translation units must be defined in the same way in all these translation units. But diagnostics is not required.

Similarly, according to the ODR, external linkage inline functions defined in multiple translation units must be defined in the same way in all those translation units. But diagnostics is not required.

In your original example, there are exactly two such entities – a class with an external linkage and an inline function with an external linkage.

Those. The language specification requires that these entities be defined in the same way in all translation units, but it's up to you to keep this same in general. An advanced compiler can help you catch such errors, but that's just a matter of implementation quality.

As soon as your function is no longer inline, diagnostics for ODR violations for such a function were immediately formally required and the compiler successfully provided it to you.

Scroll to Top