Home Articles Books Downloads FAQs Tips

What's Wrong With This Code? Volume #3


The hidden danger of overriding virtual pascal base functions

The following code overrides the virtual CreateParams function to specify the window class name of a utility form. The window class name is passed to the form in the constructor, and then stored away in a private variable. CreateParams then uses the private string variable to intialize the WinClassName member of the TCreateParams structure

//---------------------------------------------------------------
// form header file
class TForm2 : public TForm
{
__published:
private:
    AnsiString m_WndClassName;
    virtual void __fastcall CreateParams(TCreateParams & Params);
public:
    __fastcall TForm2(TComponent* Owner,
                      const AnsiString &WndClassName = "TForm2");
};

//---------------------------------------------------------------
// form cpp file
__fastcall TForm2::TForm2(TComponent* Owner,
                          const AnsiString &WndClassName)
    : TForm(Owner),
      m_WndClassName(WndClassName)
{
}
//---------------------------------------------------------------
void __fastcall TForm2::CreateParams(TCreateParams & Params)
{
    TForm::CreateParams(Params);
    strcpy(Params.WinClassName,m_WndClassName.c_str());
}

//---------------------------------------------------------------
// showing TForm2 from the main form
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TForm2 *form = new TForm2(this, "MotherPumpkin");
    form->ShowModal();
}

On the surface, it looks like this should work. However, when we run the program, an EWin32Error exception is raised during the creation of the TForm2 object. The error message box is shown in Figure 1.



Figure 1. EWin32Error

Can you find out what caused the error?


Answer


Code for this edition
wwwtc3.zip BCB4 project that contains problem code.
wwwtc3x.zip Same project, includes an EXE (188 kb).


Copyright © 1997-2002 by Harold Howe.
All rights reserved.