Inheritance Basics

Plain (Base) Class

  • A plain class Base, with a method (simply announcing itself on stdout)

  • No surprise

#include <iostream>


class Base
{
public:
    void method() const
    {
        std::cout << "Base::method()" << std::endl;
    }
};

int main()
{
    Base b;
    b.method();      // <--- calling Base::method() (obviously)

    return 0;
}
../../../../../_images/uml-base.jpg
$ ./inher-oo-base
Base::method()

Inheriting (Deriving) From Base

Note

Here we use only public inheritance. See Inheritance: private, protected (Implementation Inheritance) for more.

#include <iostream>


class Base
{
public:
    void method() const
    {
        std::cout << "Base::method()" << std::endl;
    }
};

class Derived : public Base
{
public:
    void method() const
    {
        std::cout << "Derived::method()" << std::endl;
    }
};

int main()
{
    Base b;
    b.method();      // <--- calling Base::method()

    Derived d;
    d.method();      // <--- calling Derived::method()
    
    return 0;
}
../../../../../_images/uml-derived.jpg
$ ./inher-oo-derived-novirtual
Base::method()
Derived::method()

News

  • Derived is-a base (though the usage of an is-a relationship is not at all clear yet)

  • Given an instance of Base, Base::method() is called

  • Given an instance of Derived, Derived::method() is called

Question

  • When d is of type Derived, but also (is-a) of type Base, is it true that I can use d as a Base?

  • If I use a Derived object as-a Base, what is the effect of calling method() on it?

Derived is-a Base?

#include <iostream>


class Base
{
public:
    void method() const
    {
        std::cout << "Base::method()" << std::endl;
    }
};

class Derived : public Base
{
public:
    void method() const
    {
        std::cout << "Derived::method()" << std::endl;
    }
};

int main()
{
    Derived d;
    Base* b = &d;     // <--- **is-a**: Derived is converted to Base, **without** a cast
    b->method();      // <--- **Question**: Base::method() or Derived::method()?
    
    return 0;
}
$ ./inher-oo-derived-novirtual-base-conversion
Base::method()

Answer

  • I can convert a Derived into a Base by assigning a Derived* to a Base*.

  • C++ does that automatically; I don’t need to use a type cast.

  • But still, I cannot use the actual object (remember, Derived d) through that Base* b