Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > base class and derived class having same variable

Reply
Thread Tools

base class and derived class having same variable

 
 
Rahul
Guest
Posts: n/a
 
      04-13-2008
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 ! ! !
 
Reply With Quote
 
 
 
 
raof01
Guest
Posts: n/a
 
      04-13-2008
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
private.php?do=newpm&u=
"Thoughts are but dreams till their effects be tried." -- William Shakespeare


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Casting from base to derived class in base constructor pastbin@gmail.com C++ 2 02-07-2008 02:41 PM
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 01:44 PM
Derived::Derived(const Base&) developereo@hotmail.com C++ 4 05-23-2007 09:32 AM
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 12:07 AM
Member variable with the same name in base and derived? marcwentink@hotmail.com C++ 10 08-25-2006 07:02 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57