Initialising a variable of unknown type via overloaded constructors in C++

C++ is a statically typed language, meaning that all variable types are determined before runtime. Therefore, auto keyword is not something like var keyword in javascript, which is a dynamically typed language. auto keyword is commonly used to specify types that are unnecessarily complex.

What you are looking for might be done by using C++ template class instead, which allows creating multiple versions of the class that takes different types.

This code might be the answer you're looking for.

template <typename T>
class Token {
private:
    T value;

public:
    Token(const T& ivalue) {
        value = ivalue;
    }

    void printValue() {
        std::cout << "The token value is: " << value << std::endl;
    }
};

This code would compile if some conditions are met, like the functionoperator<< should be defined for std::ostream& and type T.


Different approach, than what others have proposed, is to use templates. Here is an example:

template<class T>
class Token {
public:

    T value;

    Token(T value) :
        value(std::move(value))
    {}

    void printValue() {
        std::cout << "The token value is: " << value << std::endl;
    }
};

Then you can use your class like this:

Token<int> x(5);
x.printValue();

Initialising a variable of unknown type via overloaded constructors in C++

There is no such thing as "variable of unknown type" in C++.

What is the right way of using the auto keyword in this scenario?

auto-deduced variables have a type that is deduced from the initialiser. If there is no initialiser, then you cannot use auto. auto cannot be used for a non-static member variable. One instance of a class cannot have differently typed members than another instance.

There is no way of using auto keyword in this scenario.

Should I use a different approach altogether?

Probably. It looks like you're trying to implement a std::variant. If you need a variable to store one of X number of types, that is what you should use.

However, you may be trying to emulate dynamic typing in C++. While it may be familiar to you due to experience with Python, in many cases that is not the ideal approach. For instance, in this particular example program, all that you do with the member variable is print it. So it would be simpler to store a string in each case. Other approaches are static polymorphism as shown by Rhathin or OOP style dynamic polymorphism as shown by Fire Lancer.