base class and derived class having same variable

R

Rahul

Hi Everyone,

I have the following code,

class AA
{
public:
int i;
};

class B : public AA
{
public : int i;
};

int main()
{
B obj;
obj.AA::i = 10;
obj.B::i = 20;
cout<<obj.AA::i<< " " <<obj.B::i<<endl;
obj.i =
10; //
Isn't this ambiguous?
cout<<obj.AA::i<< " " <<obj.B::i<<endl;
return(0);
}

I expected a compilation error when obj.i is used as there are two
versions if i available in class B. How does the compiler manage to
resolve the reference to the correct i?

Thanks in advance ! ! !
 
R

raof01

Hello Rahul,
Isn't this ambiguous?
cout<<obj.AA::i<< " " <<obj.B::i<<endl;
return(0);
}

No. This is about name hiding. The scope of derived class is nested in that
of base class. So i in B hides that in AA. You can use obj.i to access B::i,
and use AA::i or using directive to make AA::i visible.

raof01
mailto:[email protected]
"Thoughts are but dreams till their effects be tried." -- William Shakespeare
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top