Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call different constructor conditionally [duplicate]

I want to call different constructor of the same class depending on a run time condition. The constructor uses different initialization list (a bunch of things after :) so I can't process the condition within the constructor.

For example:

#include <vector>
int main() {
    bool condition = true;
    if (condition) {
        // The object in the actual code is not a std::vector.
        std::vector<int> s(100, 1);
    } else {
        std::vector<int> s(10);
    }
    // Error: s was not declared in this scope
    s[0] = 1;
}

I guess I can use pointer.

#include <vector>
int main() {
    bool condition = true;
    std::vector<int>* ptr_s;
    if (condition) {
        // The object in the actual code is not a std::vector.
        ptr_s = new std::vector<int>(100, 1);
    } else {
        ptr_s = new std::vector<int>(10);
    }
    (*ptr_s)[0] = 1;
    delete ptr_s;
}

Is there a better way if I didn't write a move constructor for my class?

like image 693
hamster on wheels Avatar asked Feb 28 '17 16:02

hamster on wheels


1 Answers

An alternative solution is to create a class that the default contructor does not make the allocations, computing ( and all the hard job ) but instead, have one function for example initialize and overload it for each constructor type to do the real job.

For example:

int main() {
    bool condition = true;
    SomeClass object;
    if (condition) {
        object.initialize(some params 1)
    } else {
        object.initialize(some params 2)
    }
}

Alternatively you may want the default constructor to do something meaningful in that case make a constructor that takes an object of a certain "dummy" type e.g. DoNothing and have instead:

 SomeClass object(DoNothing())
like image 176
user183833 Avatar answered Sep 21 '22 23:09

user183833