vendredi 8 mai 2020

How to prevent a derived type from being converted to its parent type?

struct A
{};

struct B : A
{
    operator A() const = delete; // not work
};

int main()
{
    B* p_derived = new B();
    delete p_derived; // ok

    A* p_base = new B();
    delete p_base; // How to make this a compile-time error?
}

A's destructor is not virtual; so, the derived B's object shouldn't be deleted by a pointer to A.

I can't use struct B : protected A {};, because I want B to inherit all public members of A and keep them still public.

My question:

How to prevent a derived type from being converted to its parent type?

Aucun commentaire:

Enregistrer un commentaire