Re: Is it possible to overload a member variable?
In article <1189222883.300472.138960@w3g2000hsg.googlegroups.com>,
postmaschine@gmail.com says...
Hi @ all!
Is it possible to overload a member variable?
No.
Example:
class ClassA_t {
[...]
private:
int itsValue;
}
class ClassB_t : public ClassA_t {
[...]
private:
float itsValue;
}
This is not overloading -- it's hiding. I.e. the name in the derived
class hides the name in the base class.
Just want to know if such approach is usual...
It's perfectly legal, but fairly uncommon to do it with normal member
variables. OTOH, the whole point of local variables is that you can have
two (or more) with the same name without them clashing. C doesn't allow
(for example) local functions, so it doesn't have a lot of hierarchy
where one local variable hides the same name in a parent. In C++ the
class hierarchy allows a great deal more of that, but it can quickly get
confusing.
There's no such thing as a 'virtual variable', so looking up variable
names is always done based on static type rather than dynamic type, so
you get much the same effect as you do with non-virtual functions. If
you refer to an object of the derived class via a pointer to the base
class, you'll see the variable defined in the base class instead of the
one in the derived class. E.g.:
#include <iostream>
class base {
int itsValue;
public:
base(int init) : itsValue(init) {}
void increment(int amount = 1) { itsValue += amount; }
};
class derived : public base {
float itsValue;
public:
derived(float init) : base(0), itsValue(init) {}
operator float() { return itsValue; }
};
int main() {
derived value(10.0);
value.increment(1);
std::cout << value << "\n";
return 0;
}
This prints out 10 because increment modified itsValue from the base
object instead of the second itsValue we added in the derived object.
Just to answer one obvious question: no, making increment virtual
doesn't help at all either. In fact, it has absolutely no effect on this
problem -- it would only help if we added a version of increment in the
derived class, AND called increment via a pointer to the base object.
--
Later,
Jerry.
The universe is a figment of its own imagination.