tags:

views:

109

answers:

3

Say I have the following code:

struct date {
    int day;
    int month;
    int year;
};

class mydateclass {
    public: 
        int day;
        int month;
        int year;
};

mydateclass date;

date.day;

Which date variable is being referred to? The date instance named mydateclass, or the date struct?

+3  A: 

There is no ambiguity.
The code defines a structure, but it doesn't create an instance of it. When you write date.day, you are referring to a variable, and there is just a variable named date.

kiamlaluno
+2  A: 

The struct declaration is called "date". There is no object date created before mydateclass date;. Therefore, the "call" is not ambigeous.

If you want to create an object in that fashion it would be:

struct datestruct {
    int day;
    int month;
    int year;
} date;

If you would do that, your compiler should complain at mydateclass date;, as an object of that name already exists.

Note that if you want to deal with the member (e.g. static member) of a class/struct w/o having an object at hands, you need :: instead of . Such as:

struct date {
    static int day;
};

date::day;
ypnos
You guessed what I wanted to ask and answered it correctly!!!
Delirium tremens
A: 

Because date in this code is declared to be an instance of mydateclass, that's the type whose members you can access through the variable date.

A quick test with slightly modified code shows, that a variable hides the struct by the same name:

struct date {
    int day;
    int month;
    int year;
};

class mydateclass {
    public:
        int day;
        int month;
        int year;
};

int main()
{
    mydateclass date;

    date.day;

    date other_date;  //error here, because "date" does not name a type in this context
    ::date yet_another_date; //okey, because "::" means the name in question is in global scope
                             //whereas the variable named "date" is local to main
}

void foo()
{
    date other_date;  //ok here, because there is no variable called "date" in scope here
}

Whether you have a struct or a class, makes no difference to the question.

UncleBens