Raider wrote:
I have library with some class having no virtual functions and non
virtual destructor.
I want to add new member functions to this class by creating derived
class and then use derived class instances as a base class instances:
// -------- library --------
class B
{
...
}
void f(B *b)
{
...
delete b; // calls B::~B() !
}
// ------- my code --------
class D : public B
{
public:
D(...) {}
void mf(); // I have access to B's protected members!
// no new member variables!!!
}
void h()
{
D* pd = new D(...);
d.mf();
You meant pd->mf();
f( pd );
}
I think it is ugly but safe. What do you think?
It is not safe. Because of the lack of virtual destructor in the base
class, you are deleting a D as though it were a B, which is bad, bad,
bad. This lack of virtual destructor implies that the base class B was
not meant to be a polymorphic base class. If you can't change the
library, you'll need to come up with some other solution, such as
supplying a copied B object from a D object:
B* D::GetB() const
{
// Treat D as B for the copy ctor
// (assumes normal copy semantics)
B* pb = new B( *this );
return pb;
}
void Foo( D* pd )
{
pd->mf();
f( pd->GetB() );
}
(Of course, I would prefer to return a std::auto_ptr<B > from D::GetB(),
but you get the idea.)
Cheers! --M