Hello,
I have an example where I have a variable belonging to a base class, but I would like to tell the compiler that it actually belongs to a derived class. How can I do this?
Regards,
bostjanv
// base class: R0
// derived class: R1
// see function SetR1 for the problem
class R0 {
public:
int a;
};
class R1: public R0 {
public:
int b;
};
void Set(R0 &r,int a) {
r.a = a;
} // Set
void SetR1(R0 &r,int b) {
// (R1)r.b = b; // THIS DOES NOT WORK
} // SetR1
R0 r0; R1 r1;
int main(int argc, char *argv[]) {
Set(r1,22); SetR1(r1,23);
}
Hello,
Thanks for the reply. The situation is the following:
I'm trying to translate some software from a language where this is quite legitimate (Oberon-2). For example, one can declare a variable of a base class type and assign to it a value of a derived class type. Later, one can take the base class variable and say "assume the actual type is the derived class" and access the derived class components. I'm trying to figure out if there is way to perform something like that in C++.
Regards,
bostjanv
void Set(R0 &r,int b) {
r.a = a; // accessing base class variable
}
R1 r1;
int main(int argc, char *argv[]) {
Set(r1,22);
}
This is because, the references and pointers to derived class objects are type compatible with base class objects.
However, following is not possible:
1 2 3 4 5 6 7 8 9
void SetR1(R0 &r,int b) {
r.b = b; // base class reference variable trying to access derived class member function.
}
R1 r1;
int main(int argc, char *argv[]) {
SetR1(r1,22);
}
This is because, although the same references are used, the function tries to access member variable specific to R1 class. Hence compiler shall complain that the function's input parameter cannot be of R0 class. It does not know that you shall later try to access it through R1 class object.
I tried the method proposed by kbw and it worked. I think I can live with the "unsafe" caveat since the point of this is to say to the compiler "I know what I'm doing; don't complain". I only hope I won't run into some nasty surprises.
Regards, bostjanv