Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Create Forms Dynamically

 

The C++ Builder (and Turbo C++) TForm class ('Form' from now on) can be created either statically or dynamically.

 

 

 

 

 

 

When to consider creating Forms dynamically

 

Consider creating Forms dynamically when:

 

 

 

 

 

 

Do's and don'ts when creating Forms dynamically

 

When you want to dynamically create a Form

 

 

 

 

 

 

How to create a Form dynamically

 

A Form can be created dynamically as follows:

 

//Put this line among the other #includes
#include <memory>

//Your method
void __fastcall TFormMain::YourMethod()
{
  std::auto_ptr<TFormDynamic> f(new TFormDynamic(this));
  f->ShowModal();
}

 

Sure you can use a plain pointer, but then don't forget to delete it. And if you don't want to forget to delete this pointer (among others), use a std::auto_ptr.

 

Instead of passing 'this', you might sometimes consider passing '0' as an argument to the constructor of TFormDynamic.

 

 

 

 

 

Communicate with the creator of a Form

 

In the code snippet above, the Form called TFormDynamic is constructed using a pointer to the TFormMain Form. This enables the newly created TFormDynamic to be potentially able to communicate with the TFormMain.

 

 

 

 

 

Communicate with the creator of a Form in the constructor only

 

The constructor of a Form takes as an argument the TComponent that has created it. Therefore, you can easily use it locally:

 

//Put this line among the other #includes
#include <cassert>

__fastcall TFormDynamic::TFormDynamic(TComponent* Owner)
: TForm(Owner)
{
  TFormMain * const formMain = dynamic_cast<TFormMain>(Owner);
  assert(formMain!=0); //Assume cast succeeded

  //Use formMain
}

 

 

 

 

 

Communicate with the creator of a Form using a member variable

 

You can also make the TFormMain pointer a member variable of TFormDynamic:

 

//UnitFormDynamic.h

//A forward declaration
//Put it after the #includes and before the next line
class TFormMain;

class TFormDynamic : public TForm
{
__published: // IDE-managed Components
//Stuff
private: // User declarations
TFormMain * const mFormMain;
public: // User declarations
__fastcall TFormDynamic(TComponent* Owner);
};

//UnitFormDynamic.cpp

//Put this line among the other #includes
#include <cassert>

__fastcall TFormDynamic::TFormDynamic(TComponent* Owner)
: TForm(Owner),
mFormMain(dynamic_cast<TFormMain>(Owner)
{
assert(mFormMain!=0); //Assume cast succeeded

//Use mFormMain
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict