user9209957
user9209957

Reputation:

Why can't I call operator()?

I am trying to understand different topics in C++ by examples and I cannot get this example to work:

template<typename T>
class zero_init
{
    T val;
public:
    zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; }
    operator T() const { std::cout << "In operator T()\n";  return val; }
};

int main()
{
    const zero_init<int> x;
    x(); //Error!
    return 0;
}

I am obviously trying to call the operator() but it gives the error: "call of an object of a class type without appropriate operator()"

Upvotes: 0

Views: 1508

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27528

You accidentally implemented a type conversion operator and not operator(). Overload operator() like this instead (I removed the return value because you discard it in main anyway):

#include <iostream>

template<typename T>
class zero_init
{
    T val;
public:
    zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; }
    void operator()() const { std::cout << "In operator()\n"; }
};

int main()
{
    const zero_init<int> x;
    x();
    return 0;
}

If you actually need the return value, do it like this:

#include <iostream>

template<typename T>
class zero_init
{
    T val;
public:
    zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; }
    T operator()() const { std::cout << "In operator()\n"; return val; }
};

int main()
{
    const zero_init<int> x;
    auto val = x();
    return 0;
}

Upvotes: 1

Related Questions