coming from a primarily python background I have somewhat struggled with working with types in C++.
I am attempting to initialise a class variable via one of several overloaded constructors that take different types as parameters. I have read that using the auto
keyword can be used for auto declaration of a variable, however in my case it will not be initialised till a constructor is chosen. However the compiler is not happy about not initialising value
.
class Token {
public:
auto value;
Token(int ivalue) {
value = ivalue;
}
Token(float fvalue) {
value = fvalue;
}
Token(std::string svalue) {
value = svalue;
}
void printValue() {
std::cout << "The token value is: " << value << std::endl;
}
};
In python this might look like:
class Token():
def __init__(self, value):
self.value = value
def printValue(self):
print("The token value is: %s" % self.value)
What is the right way of using the auto
keyword in this scenario? Should I use a different approach altogether?
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.