Главная страница | назад

Article #20192: Why is my component giving me a "Stack Overflow" error?

Question: Why am I getting "Stack overflow" errors in my component?
Answer: One possibility is that you have recursive getters/setters. This is a commonly encountered problem that is easily remedied. If you have a getter/setter for a property that is referencing the property name, it will be recursive, generating a stack overflow.

class MyComp: public TComponent
  void __fastcall SetDead(bool val);
  bool __fastcall GetDead();
  __fastcall MyComp(TComponent *Owner);
  __property bool Dead = {read=GetDead, write=SetDead};

__fastcall MyComp::MyComp(TComponent *Owner)
  : TComponent(Owner)

void __fastcall MyComp::SetDead(bool val)
  Dead = val;

bool __fastcall MyComp::GetDead()
  return Dead;

In this example, when trying to do something like mycomp->Dead = true, the following will happen:
(1)SetDead will be called
(2)SetDead calls itself
(3)SetDead calls itself
The same will happen for GetDead. Properties are a nice extension to the C++ language, but in order to use them, they have to reference actual data. You need a private class member (bool m_Dead or something) that will hold the value. This will get rid of the stack overflow.

Last Modified: 01-DEC-99