
Derived and Base class variables
Quote:
> Can you have a variable in a derived class with the same name as in
> the base class? I.e.
> class Base
> {
> int myint;
> }
> class Derived : public Base
> {
> int myint;
> }
Yes
Quote:
> I tried it and expected the compiler to complain but it didn't. Is the
> compiler treating the second myint as merely a redeclaration of the
> first?
No.
You are declaring a new member that has the name myint
The member of the same name in the base class is still there, but you just
cannot directly access it from the derived class by name only
However you can access, for example, by prefixing the name with a class
scope
eg
void Derived::foo() {
myint = 1; // refers to myint in Derived
Base::myint = 2; // refers to myint in Base
Quote:
}
Its pretty much the same as function overloading .. the base class function
still exists, but when you use the function name (without scope etc) you get
the derived class version. Of course, with functions, you also have the
issue of virtual functions. There is no such thing as a virtual data member
though.
The means that
Derived* pDerived;
Base* pBase;
Derived x;
pDerived = &x;
pBase = &x;
pDerived->myint = 1; // refers to myint in Derived
pBase->myint = 1; // refers to myint in Base (even though pBase points to an
object of type Derived)
--
Roger Onslow
Software Developer
See my articles at http://www.codeguru.com
See the product I am working on at http://www.swishzone.com
"Operator .. give me the number for 911" .. Homer Simpson