Suggesting there's a class that is composed of objects allocated in a heap.
class A
{
public:
A() { m_b = new B; m_c = new C; }
virtual ~A() { delete m_b; delete m_c; }
inline B* b() const { return m_b; }
inline C* c() const { return m_c; }
private:
B* m_b;
C* m_c;
}
Which setters would be the best for such code?
I figured out this one,
inline void setB(B* b) const { delete m_b; m_b = b; }
inline void setC(C* c) const { delete m_c; m_c = c; }
But there's a problem. If we added a non-heap variable or just a variable we did not have to delete with this setter, it would be deleted after the next invocation of the setter and this situation would cause an error or an unexpected behavior.
We can't delete objects directly as well because getters have const
modifier. In addition, it would be not safe because an user of the class may not know whether the inner objects are allocated in a heap or not.
Could you please explain me how to use setters with heap-allocated objects?