mardi 28 novembre 2023

Why do I get the error "Expression must have class type but it has type Calculator(*)()" when I create an object?

Context:

I am learning C++ and came across the concept of delegating constructors and also member initializer lists. I was creating a very basic calculator class and I came across the error message "Expression must have class type but it has type Calculator(*)()" when creating an object.

The code for my class is

class Calculator 
{

    float num1;
    float num2;

public:
    
    Calculator() : Calculator(0, 0){}
    Calculator(float n1) : Calculator(n1, 0){}
    Calculator(float n1, float n2): num1(n1), num2(n2){}

    //declaring the facilitators
    float add(float n1, float n2);
    float subtract(float n1, float n2);
    float multiply(float n1, float n2);
    float divide(float n1, float n2);

    //destructor
    ~Calculator() {
        std::cout << "Object destroyed" << std::endl;
    }
};

The member functions are not causing any issue so I will leave out their definitions

Within the main function(), when I create my object as

Calculator obj; My program works and I can use the obj to access all the member functions. However, when I write

Calculator obj(); I get the error specified in the title.

I am confused as to why this happens. Shouldn't the default constructor (and then the third constructor through delegation) be invoked in both cases?

Aucun commentaire:

Enregistrer un commentaire