how to tell the compiler "consider this to be the derived class X"

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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);
}
When the member variable b is only specific to class R1, why do you need to declare function input variable of class R0?

Class R0 does not know anything about class R1 so it does not recognize the variable r.b.
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
AFAIK the following is possible in C++:

1
2
3
4
5
6
7
8
9
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.
If you want to override the type system and do an unsafe downcast, you do this.
1
2
3
4
void SetR1(R0& r, int b)
{
    static_cast<R1*>(&r)->b = b;
}
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
Topic archived. No new replies allowed.