1) Code tags.
2) You can't delete a void pointer to an object and have it properly work. It won't call the destructor of the class properly. Here's an example:
Code:
#include <iostream>
class CMyClass{
public:
CMyClass(){
std::cout << " Constructor" << std::endl;
}
~CMyClass(){
std::cout << " Destructor" << std::endl;
}
};
int main(){
std::cout << "First pointer:" << std::endl;
CMyClass * p = new CMyClass();
delete p;
std::cout << "Second pointer:" << std::endl;
void * p2 = new CMyClass();
delete p2;
std::cout << "End." << std::endl;
}
yields:
Code:
First pointer:
Constructor
Destructor
Second pointer:
Constructor
End.
If you need to have multiple types represented by a single pointer, create a base class (with its destructor virtual) and make the pointer a pointer to the base class. E.g.:
Code:
#include <iostream>
class CBase{
public:
CBase(){
std::cout << " Base Constructor" << std::endl;
}
virtual ~CBase(){
std::cout << " Base Destructor" << std::endl;
}
};
class CDerived : public CBase{
public:
CDerived(){
std::cout << " Derived Constructor" << std::endl;
}
~CDerived(){
std::cout << " Derived Destructor" << std::endl;
}
};
int main(){
std::cout << "First pointer:" << std::endl;
CDerived * p = new CDerived();
delete p;
std::cout << "Second pointer:" << std::endl;
CBase * p2 = new CDerived();
delete p2;
std::cout << "End." << std::endl;
}
yields:
Code:
First pointer:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Second pointer:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
End.
Of course, you can make the base constructors/destructors empty; E.g., your base class can be as simple as:
Code:
class CBase{
public:
virtual ~CBase(){}
};
All you really need is to tell the compiler that the destructor is virtual; in this way, deleting a CBase * will properly delete pointer to objects derived from CBase.