I\'m sure this is a really simple question. The following code shows what I\'m trying to do:
class MemberClass {
public:
MemberClass(int abc){ }
};
clas
Use the conditional operator. If the expression is larger, use a function
class MyClass {
public:
MemberClass m_class;
MyClass(int xyz) : m_class(xyz == 42 ? 12 : 32) {
}
};
class MyClass {
static int classInit(int n) { ... }
public:
MemberClass m_class;
MyClass(int xyz) : m_class(classInit(xyz)) {
}
};
To call a function before initializing m_class, you can place a struct before that member and leverage RAII
class MyClass {
static int classInit(int n) { ... }
struct EnvironmentInitializer {
EnvironmentInitializer() {
do_something();
}
} env_initializer;
public:
MemberClass m_class;
MyClass(int xyz) : m_class(classInit(xyz)) {
}
};
This will call do_something() before initializing m_class. Note that you are not allowed to call non-static member functions of MyClass before the constructor initializer list has completed. The function would have to be a member of its base class and the base class' ctor must already be completed for that to work.
Also note that the function, of course, is always called, for each separate object created - not only for the first object created. If you want to do that, you could create a static variable within the initializer's constructor:
class MyClass {
static int classInit(int n) { ... }
struct EnvironmentInitializer {
EnvironmentInitializer() {
static int only_once = (do_something(), 0);
}
} env_initializer;
public:
MemberClass m_class;
MyClass(int xyz) : m_class(classInit(xyz)) {
}
};
It's using the comma operator. Note that you can catch any exception thrown by do_something by using a function-try block
class MyClass {
static int classInit(int n) { ... }
struct EnvironmentInitializer {
EnvironmentInitializer() {
static int only_once = (do_something(), 0);
}
} env_initializer;
public:
MemberClass m_class;
MyClass(int xyz) try : m_class(classInit(xyz)) {
} catch(...) { /* handle exception */ }
};
The do_something function will be called again next time, if it threw that exception that caused the MyClass object fail to be created. Hope this helps :)