Paul Smitton <pa**********@mutech.co.ukwrote in message...
Hello,
I would like to be able to store some constant data that is specific to
each
descendant class.
This data would then be accessable by base class functions. However, I
cannot find out how to do this.
I thought the following would be a practical way of achieving this, but it
will not work.
Any help would be appreciated.
class Vehicle { // private:
static const int int Wheels = 0;
'int int'?
public:
int GetWheels() {
return Wheels;
}
};
class Car: public Vehicle { // private:
static const int Wheels = 4;
};
class Motorbike: public Vehicle { // private:
static const int Wheels = 2;
};
void main() {
Vehicle *myMini = new Car;
n = myMini->Wheels; // n = 0, but i was hoping it
would be 4
}
class Vehicle{
static const int Wheels = 0;
public:
virtual ~Vehicle(){} // base class
virtual int GetWheels(){
return Wheels;
}
};
class Car: public Vehicle {
static const int Wheels = 4;
public:
virtual int GetWheels(){
return Wheels;
}
};
class Motorbike: public Vehicle {
static const int Wheels = 2;
public:
virtual int GetWheels(){
return Wheels;
}
};
int main(){ // NOT void main()
Vehicle *myMini = new Car;
// int n = myMini->Wheels; // n = 0, but i was hoping it would be 4
int n = myMini->GetWheels();
cout <<"\nmyMini->Wheels="<<n<<std::endl;
delete myMini;
return 0;
} // main()
'Wheels' is private in class Vehicle, 'myMini' can't directly access it from
main().
Is there some reasom you want 'Wheels' 'static'?
If that is not just an example, you may want a separate class 'Wheel' (with
diameter, psu, color, lugnuts, etc.), and composite those into 'Vehicle'.
Re-think your design, IMHO.
--
Bob R
POVrookie