Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

USING C++ To gain a better understanding of polymorphic and virtual functions st

ID: 3692041 • Letter: U

Question

USING C++ 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 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’ll notice the second testFunction() call generates the message “Derived class”. Welcome to polymorphism!

Explanation / Answer

When I ran the program without virtual keyword for the function testFunction in base class then every time I call testFunction with ptr object pointing to either base or derived then testFunction from base class is only called.

When we use virtual keyword to the base calss function testFunction then now when we call this function with derived class object it will exceute. Thus the Polymorphism is done in c++.