1

I already read this Same name structure with different definition in C But it doesn't clear my question. Wouldn't it be better to separate declaration and definition like function? Because it is possible, following code can work.

//AAA.c
class AAA
{
public:
    // even if AAA only have 1 member variable, it works.
    char i;
    char f;
    char d;
    char e;
    void PrintAYAYA();
};

void AAA::PrintAYAYA() { std::cout << "AYAYA\n"; };
void GetAAAWhatHappen(AAA a)
{
    char* p = (char*)&(a.i);
    char arr[4]{};
    for (int i = 0; i < 4; ++i)
        std::cout << (int)*(p + i) << std::endl;

}


//main.c 
class AAA
{
public:
    int i = 0x12345678;
    void PrintAYAYA();
};

void GetAAAWhatHappen(AAA a);
int main()
{
    AAA a;
    a.PrintAYAYA();
    GetAAAWhatHappen(a);
}

Despite being distinctly different definitions, the above code runs because they share the same name

And another question, afer the compiler links the object files and create an exe file, when execute exe file, how does computer distinguish classes with the same name but different definitions?

busbug
  • 89
  • 4
  • Note that you also have `char i` and `int i` with no problem. – stark Mar 28 '23 at 16:10
  • 5
    This code violates the One Definition Rule, and is Undefined Behavior. The question you link to doesn't suffer this, because the structs there are anonymous. C++ only "allows" Undefined Behavior because it is the developer's responsibility not to do it. – Drew Dormann Mar 28 '23 at 16:13
  • Unfortunately in C++ not every code that compiles and even produces expected output is valid. – Slava Mar 28 '23 at 16:35
  • Re: "Why does C++ allow.." -- it doesn't. And the standard doesn't require compilers to do anything in particular when this is done. – Pete Becker Mar 28 '23 at 18:03

1 Answers1

7

Your code is not valid C++. Not everything that is invalid C++ produces a compiler error, you just get unpredictable behavior. Your code violates the One Definition Rule:

There can be more than one definition in a program of each of the following: class type, [...] , as long as all of the following is true:

  • each definition consists of the same sequence of tokens (typically, appears in the same header file)
  • [...]

If all these requirements are satisfied, the program behaves as if there is only one definition in the entire program. Otherwise, the program is ill-formed, no diagnostic required.

The highlighted part might be surprising, but is quite common in C++. "ill-formed" means that your program is broken. "no diagnostic required" means that a C++ compiler is not required to tell you about this fact. This is what you are seeing.

Chronial
  • 66,706
  • 14
  • 93
  • 99