Reputation: 155
e.g let we have some struct that do some mathematics with 4 numbers and we want to do some particular things with particular values in two constructors, is it possible to overload constructor in way that we don't use any additional values(sort of mode switch)?
struct Coolness
{
float a = float();
float b = float();
float c = float();
float d = float();
Coolness(float a, float b)
{
/* do stuff here*/
}
Same types here but different values
Coolness(float c, float d)
{
/* do other stuff here*/
}
};
Upvotes: 0
Views: 156
Reputation: 5321
You can use a tag struct to differentiate. For example,
struct Coolness {
struct Joe{};
struct Fonz{};
float a = float();
float b = float();
float c = float();
float d = float();
Coolness(Joe, float a_, float b_) : a{a_}, b{b_} {
/* do stuff here*/
}
Coolness(Fonz, float c_, float d_) : c{c_}, d{d_)} {
/* do other stuff here*/
}
static Coolness MakeFonz(float c, float d) {
return Coolness{Fonz{}, c, d};
}
};
int main() {
Coolness x{Coolness::Joe{}, 7.0f, -3.333f};
Coolness y{Coolness::Fonz{}, 1.0f, 2.0f};
Coolness z = Coolness::MakeFonz(3.0f, 4.0f);
}
Update: added a usage example, and added a static factory function to help illustrate how to use the technique.
Multiple static factory functions, without the tag structs, can be used to differentiate between different ways of constructing the object as well, rather than using any public constructors.
Upvotes: 2
Reputation: 3493
You can't have multiple overloads with the same signature.
An alternative is to create static methods that create the object for you. For instance, if you created your own Complex
class you could have a static method to create a complex number from the real and imaginary parts, then you could have another static method to create an object passing the absolute value and the phase.
Upvotes: 2