Reputation: 1337
I have a class MyClass
mainly based on one member Attribute
. What is the best possibility to implement optional members Optional1
and Optional2
into the class definition. The idea is that in some cases there is more information about the MyClass
-object which should be added to it.
class MyClass {
private:
double Attribute;
//double Optional1; //that's what I want to implement
//double Optional2; //that's what I want to implement
public:
MyClass(Attribute);
void setAttribute(double);
//void setOptional1(double);
//...
};
I think there is nothing like a really optional member in a class, so I probably have to deal with default values in the constructor. Something like
MyClass(Attribute, Optional1 = -1, Optional2 = -1)
If -1
is never set in a normal case, I know for sure that Optional1
and/or Optional2
"is not set". If it is different from -1, I know it has an intented value.
However, this approach seems to be a bit ugly and I wonder if there is some better way.
Upvotes: 2
Views: 1254
Reputation: 10880
You might be searching for std::optional<>
if it's runtime-optional or bool template parameter(s) if it's compile-time optional. But, first and foremost, verify your design: are we talking about the same class and not a class hierarchy?
Upvotes: 2