2

I've been given a struct that I cannot modify. Is it possible to provide my destructor and use it instead of the given one? Or maybe define my struct and then typecast it when needed? Inheritance is also an option, but didn't manage to skip call of parent destructor.

//Given struct
struct TA {
  ~TA() {
    delete m_L;
    delete m_R;
  }
  TA* m_L;
  TA* m_R;
};

//What i need
struct TB {
  ~TB() {
    if (m_L) m_L->destroy();
    if (m_R) m_R->destroy();
  }
  void destroy() {
    if (!--nRefernece) delete this;
  }
  int nRefernece;
  TB* m_L;
  TB* m_R;
};
Manu343726
  • 13,969
  • 4
  • 40
  • 75
NefariousOctopus
  • 807
  • 2
  • 10
  • 18

2 Answers2

5

No. If you don't want a parent destructor to be called, don't use inheritance.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • +1 Inheritance is not the only tool we have, use it properly. OTOH I think you should extend the answer providing a more in depth reason, and an alternative solution. – Manu343726 Mar 15 '14 at 11:13
  • 1
    @Manu343726: I wasn't quite sure what problem the author really wanted to solve, but the technical question itself was quite clear and could only be answered with a clear "no", IMO. – Christian Hackl Mar 15 '14 at 11:14
  • Also one may add the consequenses of destructor in base class not being virtual. – user2672165 Mar 15 '14 at 11:14
3

This is a dirty hack, but it is effective in your situation:
You can simply do the calls to destroy() in the destructor of a derived class, and set the variables m_L and m_R to zero before returning from your destructor. delete is defined to do nothing if passed a null pointer, so, you have effectively deactivated the code within the base class destructor.

struct TB : TA {
  ~TB() {
    if (m_L) ((TB*)m_L)->destroy();
    if (m_R) ((TB*)m_R)->destroy();
    m_L = m_R = 0;
  }
  void destroy() {
    if (!--nReference) delete this;
  }
  int nReference;
};
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106
  • So this might be motivated by reference counting? In the bigger picture it would be nice to get motivation of this. Variable name change to nReference would give better indication. – user2672165 Mar 15 '14 at 11:45
  • @user2672165 `nRefernece` was copy paste from the question. I'll fix it. Apart from that, my answer is really nothing more than a dirty hack for the specific problem of the OP. I would not recommend to write such destructors, unless you are forced to. – cmaster - reinstate monica Mar 15 '14 at 11:57
  • You sir, are a genius. :) Although it is a dirty little trick, it works like a charm in this exact case. – NefariousOctopus Mar 15 '14 at 17:49