I this a good implementation for this simple inheritance not using any virtual functions.
Why I would like this: Avoid virtual inheritance in performance crititcal code. A boost::variant could help here certainly, but I want only standard c++ stuff :-)
I refer also to this answer Link
#include <iostream>
using namespace std;
struct C;
struct B;
class A{
public:
A(int r): type(r){}
int type;
void deleter();
protected:
~A(){std::cout << "DTOR A" << std::endl;}
};
class B: public A{
public:
B():A(1){};
~B(){std::cout << "DTOR B" << std::endl;}
};
class C: public A{
public:
C():A(2){};
~C(){std::cout << "DTOR B" << std::endl;}
};
void A::deleter(){
if(type==1){
delete static_cast<B* const>(this);
}else if(type==2){
delete static_cast<C* const>(this);
}
}
int main(){
A * a = new B();
a->deleter();
}
I want to use the base pointer a
. The main problem is what to do when we want to delete a
. I simply prohibited that by making the DTOR
of A
protected. So the only way of using this construct is to call a.deleter()
to safely delete a bas class pointer.
Is this safe and a good implementation or is there a better approach?