Re: Base class returning children's data
* Alessandro [AkiRoss] Re:
On Jul 5, 2:54 am, "Alf P. Steinbach" <al...@start.no> wrote:
Well, then you run into problems if you allow variable data in those properties.
But putting that aside (just don't have that), it seems that what you're after
is the old concept of meta-class, like, off the cuff,
Thanks for the reply :) It gave me some ideas...
I'd prefer to avoid meta-classes, it seems a little code bloat to me
for such an easy (?) task. What about this? It seems to work, but...
Is it correct and safe?
It seems to be formally correct (disclaimer: haven't compiled).
However it's just plain ordinary direct dynamic polymorphism.
If that's what you want, OK, but then the original question is difficult to grok.
class Base {
// This is the function I'd like to write only once
const int get() { return val() * 100 + 5; }
Here it's not meaningful to apply 'const' to the result value.
Instead it would be meaningful to apply 'const' to the function.
private:
virtual int val() {
static const int myVal = 10;
return myVal;
}
Here the named static constant has no purpose. Just write
virtual int val() { return 10; }
or
virtual int val() const { return 10; }
};
class Deri: public Base {
private:
virtual int val() {
static const int myVal = 20;
return myVal;
}
};
int main(int argc, char **argv) {
Base *o1 = new Base(),
*o2 = new Deri();
cout << "O1 val: " << o1->get() << endl
<< "O2 val: " << o2->get() << endl;
return EXIT_SUCCESS;
}
I mean, get() will always refer to polymorphic (overwritten virtual)
val()?
Yes.
Actually I'm having some difficulties in figuring out *why* this
works :D
It's just plain ordinary direct dynamic polymorphism.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?