Exam 15: Polymorphism and Virtual Functions
It is legal to have all member functions of a class be pure virtual functions.
True
Write a program where the destructors should be virtual.Explain.
The requested code and further discussion follow.
#include<iostream>
using namespace std;
class B
{
public:
B():bPtr( new int[5]){ cout << "allocates 5 ints\n";}
virtual ~B()
{ delete[] bPtr;cout << "deallocates 5 ints\n";}
private:
int * bPtr;
};
class D:public B
{
public:
D():B(),dPtr(new int[1000]){cout << "allocates 1000 ints\n";}
~D(){ delete[] dPtr;cout << "deallocates 1000 ints\n";}
private:
int * dPtr;
};
int main()
{
for (int i = 0;i < 100;i++)
{
B* bPtr = new D;
delete bPtr;
}
cout << "\nWithout virtual destructor,\n";
cout << "100 * 1000 + 500 ints allocated\n"
<< "but only 500 ints deallocated.\n";
cout << "\nWith virtual destructor,\n";
cout << "100 * 1000 + 500 ints allocated,and "
<< "100 * 1000 + 500 ints deallocated.\n";
}
In this code,if the base class destructor is not virtual,the system must bind the pointer to the destructor at compile time.The pointer in main,bPtr,is of type B*,i.e. ,pointer to B,so it is bound to B's member functions.The destructor for D,~D fails to run.
If the keyword virtual is removed from the destructor in the base class,class B,the derived class destructor ~D is not called.Approximately 400K of memory would then be leaked.
Write a class having a public pure virtual method.You need not put any other members in the class.
A derived class destructor always invokes the base class destructor.
It is desirable to develop your programs incrementally.Code a little,test a little.If you do this with virtual functions,you get into trouble.Discuss the problem and the (very simple)solution.
A class that has a pure virtual member function is called a concrete base class.
Suppose each of the base class and the derived class has a member function with the same signature.Suppose you have a base class pointer to a derived class object and call the common function member through the pointer.Discuss what determines which function is actually called,whether the one from the base class or the one from the derived class.Consider both the situations where the base class function is declared virtual and where it is not.
A pointer to objects of a derived class can be assigned pointers to objects of the base class in the inheritance hierarchy.
A the binding of virtual function is done at runtime if called using an object.
It is OK to assign between objects of base type and objects of derived type.
Virtual functions are implemented with a table look up that is done at run time.
No objects can be defined of abstract base class type since it is an incomplete definition.
Which functions in class D are virtual?
class B
{
public:
virtual void f();
virtual void g();
// ...
private:
//...
};
class D : public B
{
public:
void f();
void g(int);
private:
// ...
};
Filters
- Essay(0)
- Multiple Choice(0)
- Short Answer(0)
- True False(0)
- Matching(0)