Margareth Reena Margareth Reena - 11 months ago 38
C++ Question

C++ member variable initialization, but first do some work inside it

I have the following class:

class MyClass {
public:
MyClass(string something);
~MyClass();
private:
some_namespace::some_class_name my_variable_name;
};


with the following constructor definition:

MyClass::MyClass(string path) {
string other = "jwrhkfg";
my_variable_name = some_namespace::some_class_name(path+other)
}


I'm trying to initialize
my_variable_name
to something dependent on
path
. I know I could use initializer list:

MyClass::MyClass(string path) : my_variable_name(path+other) {}


But what if I need to do a lot of processing on top of the
path
string and then initialize
my_variable_name
? What if I need to do something like this:

MyClass::MyClass(string path) {
string other = "jwrhkfg";

if (path="site.com") {
other = "oritrot";
} else {
other = "hsghkr";
}

my_variable_name = some_namespace::some_class_name(path+other)
}


I cannot put these
if
s in an initializer list.

I thought the code above would work because I only declared the name
my_variable_name
but didn't define it, so I could do in the constructor, but when I do:

MyClass my_object = MyClass("some_string");


I get that there's no constructor for
some_class_name
(because the default constructor takes one argument, and here it is trying to initialize even if I didn't initialize it, only declared.

Answer Source

Make your member a smart pointer instead:

class MyClass {
    public: 
        MyClass(string something);
        ~MyClass();
    private:
        std::unique_ptr<some_namespace::some_class_name> my_variable_name;
};

MyClass:MyClass(string path) {
    string other = "jwrhkfg";
    my_variable_name = std::make_unique<some_namespace::some_class_name>(path+other);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download