Inheritance Basics¶
Plain (Base) Class¶
A plain class
Base
, with amethod
(simply announcing itself onstdout
)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;
}
$ ./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;
}
$ ./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 calledGiven an instance of
Derived
,Derived::method()
is called
Question
When
d
is of typeDerived
, but also (is-a) of typeBase
, is it true that I can used
as aBase
?If I use a
Derived
object as-aBase
, what is the effect of callingmethod()
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 aBase
by assigning aDerived*
to aBase*
.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 thatBase* b