I put std::optional in the constructor of a class. But when I make an instance of that class, leaving out the optional argument, I get the error that no such constructor exists for that class. I would like to know how to properly use std::optional.
The constructor for my class 'Car' looks like this:
Car::Car(string make, string model, Racer *driver, optional<Racer*> codriver) : m_make(make), m_model(model), m_driver(driver), m_codriver(codriver)
{
}
This is what my main looks like:
void main()
{
Racer *r1 = new Racer{ "John Doe", "male", "08/05/1987", "Ford" };
Racer *r2 = new Racer{ "Jane Doe", "male", "06/09/1990", "Ford" };
Racer *r3 = new Racer{ "Howard", "male", "18/04/1985", "Dodge" };
Car c1{ "Ford", "Mustang GT350R", r1, r2 };
Car c2{ "Dodge", "Challenger SRT Hellcat RedEye", r3 };
}
I expected that using optional would allow me to not have to provide a co-driver when making a new instance of Car. This however does not seem to be the case since I'm getting an error that there is no such constructor.
You can set a default argument for the option:
Car(string make, string model, Racer *driver, optional<Racer*> codriver=std::nullopt)
: m_make(make), m_model(model), m_driver(driver), m_codriver(codriver) { }
But as Deduplicator said, this can also be done by using pointers as an option type (null/not-null):
Car(string make, string model, Racer *driver, Racer* codriver=nullptr)
: m_make(make), m_model(model), m_driver(driver), m_codriver(codriver) { }
For what you want to do, it seems like setting a default value in the public section of your class should work, as in the following (code taken from this question):
class foo
{
private:
std::string name_;
unsigned int age_;
public:
foo() :
name_(""), // Set your default values here
age_(0)
{
}
foo(const std::string& name, const unsigned int age) :
name_(name),
age_(age)
{
...
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With