To gain a better understanding of polymorphic and virtual functions start with t
ID: 654006 • Letter: T
Question
To gain a better understanding of polymorphic and virtual functions start with the following simple example. Notice we have not defined a virtual function yet.
// Task1.h
#include <iostream>
using std::cout;
using std::endl;
class Base
{
public:
void testFunction ();
};
class Derived : public Base
{
public:
void testFunction ();
};
// Task1.cpp
#include "Task1.h"
void Base::testFunction ()
{
cout << "Base class" << endl;
}
void Derived::testFunction ()
{
cout << "Derived class" << endl;
}
// main.cpp
#include "Task1.h"
int main(void)
{
Base* ptr = new Base;
ptr -> testFunction (); // prints "Base class"
delete ptr;
ptr = new Derived;
ptr -> testFunction (); // prints "Base class" because the base class function is not virtual
delete ptr;
return 0;
}
Now modify the code with the following (all other code should remain the same).
class Base
{
public:
virtual void testFunction ();
};
Compile and run your program with this modification. You
Explanation / Answer
#include <iostream>
using std::cout;
using std::endl;
class Base
{
public:
virtual void testFunction();
};
class Derived : public Base
{
public:
void testFunction();
};
void Base::testFunction()
{
cout << "Base class" << endl;
}
void Derived::testFunction()
{
cout << "Derived class" << endl;
}
// main.cpp
int main(void)
{
Base ptr = new Base;
ptr.testFunction (); // prints "Base class"
delete ptr;
ptr = new Derived;
ptr.testFunction(); // prints "Base class" because the base class function is not virtual
delete ptr;
return 0;
}