views:

38

answers:

2

In the followint code, how does the pointer conversion & multi-inheritance play together?

class Foo {
  public:
  virtual void someFunc();
};

class Bar;


void someWork(Bar *bar) {
  ((Foo*) bar)->someFunc();
}

class Bar: public Zed, public Foo {
...
virtual void someFunc() { ... do something else ... }
}

Bar bar;

int main() {
  someWork(&bar);
}

My understanding is kinda shaky.

On one hand, someWork knows nothing about Bar, so this shouldn't work; but on the other hand, I have forward declared Bar.

Thanks!

A: 

Hmm. My guess is that since the cast is "evaluated" during linking, which is after the class has been compiled. But that's just a guess.

Narfanator
+5  A: 

This doesn't work and it isn't doing quite what you think it is. Your use of the c-style cast:

(Foo*) bar

is incorrect in this case. What you are trying to do is upcast the Bar* to a Foo* (i.e., perform a static_cast from a pointer to a dervied class to a pointer to a base class).

Since the definition of Bar is not available at this point, however, the compiler does not know that Foo is a base class of Bar. Thus, the static_cast fails and the compiler falls back and uses a reinterpret_cast, which is not at all the same thing.

James McNellis
I can not upvote you enough.
anon