JanBTG
JanBTG

Reputation: 1

Multiple, varying Constructors as Function Parameters

i got something like this:

class Object{  
    A a;
    B b;
    C c;
}

A certain class called Object, which has three propertys. A,B and C are structs in my case. The constructor of Object looks something like this:

Object::Object(A a, B b, C c)
{
    this->a = a;
    this->b = b;
    this->c = c;
}

What im trying to reach is, that the user can call the constructor of Object and set any of these values, while the rest of them should stay on some default value.

For example those function calls should be working somehow:

int main() {
    Object(A(),B(),C());  
    Object(A());            // B and C stay on some default value
    Object(A(),C());        // B stays on some default value
}

I allready tried it with c++ default parameters. That didn't work, because it is impossible to supply a user-defined value for B() without also supplying a value for A().

Anyways, the code above is just a simplified example. My code should be extensible. There might be Objects with more than three values in the future, and i dont want to create a different constructor for every possible call case.

Do you have any ideas on this? Is there any possibility to do this?

Upvotes: 0

Views: 37

Answers (1)

MatiasFG
MatiasFG

Reputation: 576

Try the builder pattern, check it on wikipedia, right here on SO and yet another reference:

For C++ it would be something like:

class A;
class B;
class C;

class Obj {
    static Obj Obj::Build() { return Obj(); }

    Obj & SetA(...) { ... }
    Obj & SetB(...) { ... }
    Obj & SetC(...) { ... }

    //...
};

main() {
    Obj o = Obj::Build()
        .SetA(<params to A>)
        .SetC(<params to c>);
    //Note: B was not named.
}

Upvotes: 1

Related Questions