I don't know how to correctly free obj2 in this code sample below, I tried using virtual destructor but exception was raised regarding the char pointer m_s not being allocated.
#include <iostream>
using namespace std;
class A
{
private:
char *m_s;
public:
A() { m_s = strdup("default"); }
A(char *s) { del_data(); m_s = strdup(s); }
A(const A& a) { del_data(); m_s = strdup(a.m_s); }
virtual void prepare() { cout << "A "; }
void display() {
prepare();
cout << m_s << endl;
}
void del_data()
{
if (m_s)
{
free(m_s);
}
m_s = nullptr;
}
virtual ~A()
{
del_data();
}
};
class B : public A
{
public:
B(char *s) : A(s) { }
B(const B &b) : A(b){}
void prepare() { cout << "B "; }
~B() {
A::del_data();
}
};
void foo(A *obj1, A obj2) {
obj1->display();
obj2.display();
}
int main() {
B obj1("text");
A *obj2 = new B(obj1);
foo(&obj1, *obj2);
delete obj2;
return 0;
}
When I delete obj2, the destructor of class B should be called and and del_data() method should free memory allocated and set m_s to nullptr. Somehow it does not work as intended, I've even tried using delete[] to no avail.
I would love to know what I'm doing wrong and how to avoid this mistake in the future.
Thank you for your time.