rok
rok

Reputation: 2765

confused about struct an class with same name

I'm reviewing some c++ code and facing an issue I don't understand. I have multiple cpp files, a main.cpp with:

#include <iostream>
#include "classtest.h"
#include "test2.h"

using namespace std;

int main() {
foo test;
test.b=5;
...

Look at the includes, test2.h is empty, and test2.cpp contain just this:

struct foo{
    int a;
};

The other header included, classtest.h contains this:

using namespace std;

class foo{
public:
    int a;
    int b;
};

As you can see there is a class and struct with the same name. My question is: why type foo in my main method is the struct and not the class? It is not defined in the header test2.h, how can main access it? Second question: given foo is the struct (I'm using eclipse and see it positioning mouse cursor on it), how can be accessible the field b, that doesn't exist for the struct? Sorry but I'm quite newbie in c++, I need to clarify this doubt. Thank you.

Upvotes: 1

Views: 206

Answers (3)

eerorika
eerorika

Reputation: 238321

why type foo in my main method is the struct and not the class?

It is not the foo that was defined in test2.cpp. You include the defnition from classtest.h, so that is what is used in main.

It is not defined in the header test2.h, how can main access it?

It doesn't, and it can not access a definition that is not included.

Second question: given foo is the struct

This premise is wrong.

how can be accessible the field b, that doesn't exist for the struct?

Because, as we have concluded, foo is the one that was defined in classtest.h.


Note, that if you would link together the object files from both main.cpp and test2.cpp, there would be two conflicting definitions for foo. Therefore the program would be violating the one definition rule and it would be ill-formed.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234685

Aside from #include <iostream>, if you substitute the #includes manually, you end up with this for main.cpp:

#include <iostream>
using namespace std;
class foo{
public:
    int a;
    int b;
};
using namespace std;
int main() {
foo test;
test.b=5;

Hence it's abundantly clear that foo is the class. There's nothing fishy going on here at all.

Upvotes: 3

user975989
user975989

Reputation: 2648

You are seeing the class foo from classtest.h, not from test2.cpp. In C++, there is no difference between a class and a struct apart from the default member access (public for struct,privateforclass`).

That's why you have the member b in your instance of foo. The reason the code compiles and links fine is because both foos are not defined at the same time. Only one is defined per translation unit.

Upvotes: 1

Related Questions