Ulkra
Ulkra

Reputation: 13

Have I to create a Object to use a class method in c++?

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.

Upvotes: 1

Views: 102

Answers (2)

Tryer
Tryer

Reputation: 4050

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);
}

Upvotes: 3

Remy Lebeau
Remy Lebeau

Reputation: 595349

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);

Upvotes: 6

Related Questions