w07-bsc-inheritance-basics
Inheritance basics
In this example, we explore the basics of Inheritance in C++. Go into
tehpc/basics/
. Consider the following code:
inheritance_basics.cpp
In total there are three classes implemented in the file. Shape
,
Ellipse
and Rectangle
. The classes Ellipse
and Rectangle
are
the derived classes that inherit from the class Shape
.
Compile the code
- load appropriate modules by performing the following command in your terminal:
source tehpc/tools/tehpc_load_modules.sh
. - go into the
tehpc/build/
folder (possibly in another terminal) - type: either
cmake -DCMAKE_BUILD_TYPE:STRING=Debug -DTEHPC_BASICS:STRING=ON ..
orccmake ..
and make sure that build type isDebug
andBasics
are ON (you only have to do this the very first time). - type:
make
(do this whenever you want to recompile). - To run the complied code, go into
tehpc/build/basics/
. - type:
./inheritance_basics
.
Obeserve the output and the implementation in the file
inheritance_basics.cpp
and answer the following questions as comments direclty on your MR.
-
In the example
inheritance_basics.cpp
, an instance namedcircle
of the classEllipse
is created. Even though the functiongetName
is defined in the classShape
, the instancecircle
is able to access the function and print the correct name of the object in the main. How is this possible? What concept of inheritance is being used here? -
Within the class
Shape
a function definitionvirtual double getArea()=0
is given. What is special about this function definition? How does it affect the child classesEllipse
andRectangle
. -
An instance named
square
of the classRectangle
is also created in themain
. We call the functioncontains
oncircle
as well as onsquare
. For thecircle
, the output message says that it contains the point. This is exactly the behaviour of the functioncontains
in the classEllipse
. However, for the instancesquare
the output message says thatfunction not implemented for square
. As you will notice, the classRectangle
does not have a functioncontains
defined. What is happening here? Why we do not see a compilation error ifcontains
is not defined for the classRectangle
?