The code below defines a virtual base class VirtualBase and a
derived class Derived which implements it. The VirtualBase
interface is simply to set and get an integer value. The Derived
adds a method for printing the value. We then have two functions in
the global namespace, printTheValue1() and printTheValue2(), which print out the values in different ways: the
first simply uses the get method of the interface to retrieve the
value; the second tries to transform the VirtualBase interface
pointer passed as argument to a pointer to the Derived class,
and then calls the Derived class' print method.
// this program does not compile! #include<iostream> class VirtualBase { public: virtual ~VirtualBase() { } virtual void setValue(int i) = 0; virtual int getValue(void) = 0; }; class Derived : public virtual VirtualBase { public: ~Derived() { } void setValue(int i) { theValue = i; } int getValue(void) { return theValue; } void printValue(void) { std::cout << "Derived::printValue(): value is " << theValue << std::endl; } private: int theValue; }; void printTheValue1(VirtualBase* v) { std::cout << "printTheValue1(): value is " << v->getValue() << std::endl; } void printTheValue2(VirtualBase* v) { Derived* d = v; d->printValue(); } int main(int argc, char** argv) { int ret = 0; Derived d; VirtualBase* v = &d; v->setValue(1); printTheValue1(v); printTheValue2(v); return ret; }The desired output is:
printTheValue1(): value is 1 Derived::printValue(): value is 1However, the program fails to compile with the error:
virtual2.cxx: In function 'void printTheValue2(VirtualBase*)': virtual2.cxx:31: error: invalid conversion from 'VirtualBase*' to 'Derived*' virtual2.cxx:31: error: cannot convert from base 'VirtualBase' to derived type 'Derived' via virtual base 'VirtualBase'What has gone wrong? How can you fix this program? [Hint: look at C++ casting operators]