Hi,
today i found a problem with destructor, when i try delete a class that was casted to its interface delete instruction don't call the class destructor before remove the instance of class from memory.
I post a simple code that explain the problem
Interface
class ITest
{
public:
virtual void Foo() = 0;
};
Implementation
class TestClass : public ITest
{
public:
TestClass()
{
Serial.println("Constructor called");
}
~TestClass()
{
Serial.println("Destructor called");
}
void Foo()
{
Serial.println("Foo called");
}
};
main
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("- Test class not casted");
TestClass* class1 = new TestClass();
class1->Foo();
delete class1;
Serial.println();
Serial.println("- Test class casted to ITest interface");
ITest* class2 = new TestClass();
class2->Foo();
delete class2;
delay(20000);
}
Output
- Test class not casted
Constructor called
Foo called
Destructor called
- Test class casted to ITest interface
Constructor called
Foo called
How fix this? Did I design the program badly?