1

I'm trying to create a simple Form in C++Builder, and I'm trying to create an adding() method in a class, but if I can, I don't want to create an object just to use a method that doesn't save any values.

This is the source of the class file:

class Op{
public:
    double adding(double x, double y);
};

double Op::adding(double x, double y){
    return x + y;
}

And this is the action that calls the button:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    double value1 = text1->Text.ToDouble();
    double value2 = text2->Text.ToDouble();
    double result = Op.adding(value1, value2);
}

But I get a compile error:

improper use of typedef 'Op'

If I have to create the object like Op operations;, please tell me how.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ulkra
  • 13
  • 5
  • Make your function `static`, and call it like `Op::adding();` – alexisrdt Feb 23 '18 at 00:00
  • Try `Op{}.adding(value1, value2);` – Killzone Kid Feb 23 '18 at 00:02
  • Note that the `Op{}` syntax is introduced in C++11, which requires C++Builder's [Clang-based compilers](http://docwiki.embarcadero.com/RADStudio/en/Clang), and not its [Classic compiler](http://docwiki.embarcadero.com/RADStudio/en/BCC32). – Remy Lebeau Feb 23 '18 at 00:04
  • 2
    If the function has nothing to do with the class, why does it have to be a member? – Bo Persson Feb 23 '18 at 00:05
  • Because i need a file to save all of my methods, i cannot put all of my Utilities in the same file as "main". But maybe i should consider using a namespace instead of class. – Ulkra Feb 23 '18 at 00:56

2 Answers2

6

For what you are attempting, declare adding() as static:

class Op{
public:
    static double adding(double x, double y);
};

Then you can call it like this:

double result = Op::adding(value1, value2);

If you don't declare it as static, you do indeed need to create an object first, eg:

Op operation;
double result = operation.adding(value1, value2);

Or:

double result = Op().adding(value1, value2);

Or, if using one of C++Builder's Clang-based compilers:

double result = Op{}.adding(value1, value2);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
3

In general, if you are only defining functions in a class and no data, it is better to consider using namespaces instead of classes. Please see this thread: Using a function pointer from one class in a function of another class

In this case you may consider the following design:

namespace Op{//this will go into a header file
    double adding(double x, double y){
        return x + y;
    }
    //define other functions as required
};

//usage in .cpp implementation file
//include the header file containing the namespace 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    double value1 = text1->Text.ToDouble();
    double value2 = text2->Text.ToDouble();
    double result = Op::adding(value1, value2);
}
Tryer
  • 3,580
  • 1
  • 26
  • 49