C++ Builder Tutorials

C++ Builder: Write your own Classes

In C++, a class is declared with the "class" keyword, a name, and (optionally) an inheritance.

Advice: if you don't specify the inheritance, some unexpected behavior might show up.

Here’s an example:

class TStudent : public TObject {
  private:
    String FName;
    float FGrade;
  public:
    void SetName(String s) { FName = s; };
    void SetGrade(float x) { FGrade = x; };
    String GetName() { return FName; };
    float GetGrade() { return FGrade; };
};

This class has private data and uses public setter and getter methods to access the internal (private) data.
It inherits from the predefined class TObject.

Example of use:

TStudent *Student = new TStudent;
Student->SetName("Jones, Jenny");
Student->SetGrade(78.5);

Properties

Properties allow you to write cleaner code. They also let you perform some specific action when the property is written to or read.

The code to make use of our class TStudent isn't very elegant.
If we rewrite the class using "properties", the declaration looks like this:

class TStudent : public TObject {
  private:
    String FName;
    float FGrade;
    void SetName(String s) { FName = s; };
    void SetGrade(float x) { FGrade = x; };
  public:
    __property String Name = { read = FName, write = SetName };
    __property float Grade = { read = FGrade, write = SetGrade };
};

This allows us to directly read from and write to these properties, thus we can write stuff like this:

Student->Name = "John";
S = Student->Name;


Example project

Here's a simple project to illustrate our class TStudent.

Place the declaration of class TStudent before the existing declaration of the form, so it can be accessed from anywhere in the unit.

The complete code is as follows:

class TStudent : public TObject { // inherits from TObject
  private:
    String FName;
    float FGrade;
    void SetName(String s) { FName = s; };
    void SetGrade(float x) { FGrade = x; };
  public:
    __property String Name = { read = FName, write = SetName };
    __property float Grade = { read = FGrade, write = SetGrade };
};

TForm1 *Form1;

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  TStu *Student = new TStudent;
  Student->Name = "Jones, Jenny";
  Student->Grade = 78.5;
  Label1->Caption = Student1->Name + ": " + FloatToStr(Student1->Grade);
  delete Student;
}

See also:

  OOP in C++