Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Ambiguous upcasting

What happens, in the above diagram, if you want to cast a pointer to an mi to a pointer to a Base? There are two subobjects of type Base, so which address does the cast produce? Here’s the diagram in code:

//: C22:MultipleInheritance1.cpp
// MI & ambiguity
#include "../purge.h"
#include <iostream>
#include <vector>
using namespace std;

class MBase {
public:
  virtual char* vf() const = 0;
  virtual ~MBase() {}
};

class D1 : public MBase {
public:
  char* vf() const { return "D1"; }
};

class D2 : public MBase {
public:
  char* vf() const { return "D2"; }
};

// Causes error: ambiguous override of vf():
//! class MI : public D1, public D2 {};

int main() {
  vector<MBase*> b;
  b.push_back(new D1);
  b.push_back(new D2);
  // Cannot upcast: which subobject?:
//!  b.push_back(new mi);
  for(int i = 0; i < b.size(); i++)
    cout << b[i]->vf() << endl;
  purge(b);
} ///:~

Two problems occur here. First, you cannot even create the class mi because doing so would cause a clash between the two definitions of vf( ) in D1 and D2.

Second, in the array definition for b[ ] this code attempts to create a new mi and upcast the address to a MBase*. The compiler won’t accept this because it has no way of knowing whether you want to use D1’s subobject MBase or D2’s subobject MBase for the resulting address.

Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]