Pure Virtual Destructor in C++
As you know virtual destructor are possible in C++, but what about the pure virtual destructor ??
Compile this file.
Is it compiled ? YES. There is no compilation error in the program.
Now try to run the same.
Interesting thing to notice here is LINKING. Linking failed with an error :
error LNK2019: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ) referenced in function "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ)
What is problem here?
Answer : Actually Destructor are called in revere order i.e. Drived class destructor called first and the base. So compiler always inject the code to call base destructor from drive class destructor. So linker gets confused when he didn't find any definition for base destructor.
So correct version of program is :
#include "iostrem"
#include "conio.h"
using namespace std;
class A
{
public:
A(){};
virtual ~A() = 0;
};
class B : public A
{
public:
B(){};
~B(){};
};
void main()
{
B a;
_getch();
}
Compile this file.
Is it compiled ? YES. There is no compilation error in the program.
Now try to run the same.
Interesting thing to notice here is LINKING. Linking failed with an error :
error LNK2019: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ) referenced in function "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ)
What is problem here?
Answer : Actually Destructor are called in revere order i.e. Drived class destructor called first and the base. So compiler always inject the code to call base destructor from drive class destructor. So linker gets confused when he didn't find any definition for base destructor.
So correct version of program is :
class A
{
public:
A(){};
virtual ~A() = 0;
};
A::~A()
{
}
class B : public A
{
public:
B(){};
~B(){};
};
void main()
{
B a;
_getch();
}
Comments
Post a Comment