15-22

Write a class with three overloaded virtual functions. Inherit a new class from this and override one of the functions. Create an object of your derived class. Can you call all the base class functions through the derived-class object? Upcast the address of the object to the base. Can you call all three functions through the base? Remove the overridden definition in the derived class. Now can you call all the base class functions through the derived-class object?

Solution:

The answers are; yes, yes, yes! Virtual functions are inherited. Only if you override one will it replace the inherited one. The compiler generates the virtual function table with the most-derived functions that apply to a class, as you would expect. In the example below, if you were to remove the definition of Derived::f( ), then Base::f( ) would be called automatically.
Code:
//: S15:InheritVirtuals.cpp
#include <iostream>
using namespace std;

class Base {
public:
    virtual void f() {
        cout << "Base::f()\n";
    }
    virtual void g() {
        cout << "Base::g()\n";
    }
    virtual void h() {
        cout << "Base::h()\n";
    }
};

class Derived : public Base {
public:
    virtual void f() {
        cout << "Derived::f()\n";
    }
};

int main() {
    Derived d;
    Base* bp = &d;
    bp->f();
    bp->g();
    bp->h();
}

/* Output:
Derived::f()
Base::g()
Base::h()
*/
///:~
Firstable, I can see that virtual functions in the base class are NOT overloaded in this code. (here are 3 different functions instead)
The next thing, in main, I can see just the calls by upcasting. There's no common calls by derived-class object, like d.f().

Well, if these virt.functions had been overloaded and than one of them overrided(in derived-class), it couldn't be possible to access any of the base class functions through the derived-class object anymore, ok? (because of name hiding)

On the other hand, if I upcast the address of the object to the base, I could access those base functions which are not overrided in derived-class, and for that which is overrided, version from derived class would be called, ok?

Finally, if I remove the overridden definition in the derived class, I can access all the base class functions through the derived-class object, ok?

So, my answers would be no, no, yes;

Correct?


TVM