I have read this article here: When to use virtual destructors? and I got the idea that, whenever we create an object dynamically using new
or smart pointers, the base class should have a proper virtual
destructor for destruction of objects at deletion.
Then I have found some code like follows(Simplified form), which has missed the virtual
destructor in the Base
:
class Base
{
public:
// some static members
};
class Derived1 final : public Base
{
public:
// other members
// default constructor does not construct the `Base` in constructor member intilizer
Derived1() {};
virtual ~Derived1() = default;
};
class Derived2 final : public Base
{
public:
// other members
Derived2() {}; // default constructor does not construct the `Base`
~Derived2() = default;
};
int main()
{
// creating Derived1 dynamically // 1
Derived1 *d1Object = new Derived1{};
// creating Derived2 dynamically // 2
Derived2 *d2Object1 = new Derived2{};
// creating Derived2 statically // 3
Derived2 d2Object2{};
// clean up
delete d1Object;
delete d2Object1;
}
My qestion is:
- Do I have Undefined Behavior in any of the cases(
1, 2, 3
) ? Why? - Isn't essential to construct the
Base
, in the member initializer lists of the constructors of the both derived classes(in the above particular case)?
I am using C++11.
Aucun commentaire:
Enregistrer un commentaire