Search code examples
c++classtemplatesconstructordefault-constructor

C++ - empty template class constructor does not initialize value


I have 2 constructors in my self-made template class. One is the empty constructor, which initializes the value to 0. In the other constructor, you can pass a value, which initializes the value to this passed value. If I use the empty constructor to make an instance of this class, it doesn't recognize the value. Why is this and how should I do this the correct way?

#include <iostream>


template <typename T>
class A {
protected:
    T value;

public:
    A()
    : value(0)
    {};

    A(T value)
    : value(value)
    {};

    ~A ()
    {};

    T get_value()
    {
        return value;
    }
};


int main(int argc, char* argv[])
{
    A<double> a(3);
    A<double> b();
    std::cout << a.get_value() << std::endl; // 3
    std::cout << b.get_value() << std::endl; // error: request for member 'get_value' in 'b', which is of non-class type 'A<double>()' std::cout << b.get_value() << std::endl;
    return 0;
}

Solution

  • b should be allocated this way, without parens:

    A<double> b;