Manthan Tilva
Manthan Tilva

Reputation: 3277

struct with same name but different member in C++

As per book The C++ Programming Language (Bjarne Stroustrup), in section 15.2.3 (The One definition rule) page no 425, I write program as below :

file1.cpp

struct S2 { int a; char b; };

file2.cpp

struct S2 { int a; char bb; };
int main(){ return 0;}

To compile I tried below command.

g++ -std=c++11 file1.cpp file2.cpp

and

clang++ -std=c++11 file1.cpp file2.cpp

Both these command producing executable with out any error or warning. But as per book this example should give error.

Upvotes: 9

Views: 2489

Answers (1)

Destructor
Destructor

Reputation: 14438

One Definition Rule says that:

if one .cpp file defines struct S { int x; }; and the other .cpp file defines struct S { int y; };, the behavior of the program that links them together is undefined.

So, your program invokes undefined behaviour (UB). So, compiler isn't required to give diagnosis for this.

If you want know the reason behind it then read this.

Hope it helps. :)

Upvotes: 14

Related Questions