...
In this non-compliant example, a pointer to the base class Base is used to refer to a Derived object. When b is deleted, undefined behavior results. Typically, the destructor for Base is invoked rather than the destructor for Derived. As a result, the object b refers to is not properly destroyed.
| Code Block | ||||
|---|---|---|---|---|
| ||||
class Base {
public:
Base() {
// Build Base object
}
~Base() {
// Destroy Base object
}
};
class Derived : public Base {
public:
Derived() {
// Build Derived object
}
~Derived() {
// Destroy Derived object
}
};
void function(void) {
Base *b = new Derived();
// ...
delete b;
}
|
...
To correct this example, the destructor for Base should be declared virtual. This ensures that the object b refers to is correctly evaluated at runtime and that deleting b will call the destructor for class Derived.
| Code Block | ||||
|---|---|---|---|---|
| ||||
class Base {
public:
Base() {
// Build Base object
}
virtual ~Base() {
// Destroy Base object
}
};
class Derived : public Base {
public:
Derived() {
// Build Derived object
}
~Derived() {
// Destroy Derived object
}
};
void function(void) {
Base *b = new Derived();
// ...
delete b;
}
|
...