I am very new to C ++, so I'm trying to figure out how to do things right in C ++. I have a class that uses one of two members. which is determined at instantiation. It looks like
main() {
shared_pointer<A> a = make_shared<A>();
if ( checkSomething ) {
a->setB(make_shared<B>());
} else {
a->setC(make_shared<C>());
}
a->doStuff();
class A {
public:
doStuff() {
}
setB( B* p ) { m_b = p; }
setC( C* p ) { m_c = p; }
B* m_b;
C* m_c;
}
}
B and C are some classes with doStuff() member function
There are many members like doStuff. Ideally, I would not check the nullptr value in each of them. What is the best / most efficient / fastest way to create a switch between the two members?
Is there a way to use a static pointer so that I have a member
static **int m_switch;
and do something like
m_switch = condition ? &m_b : &m_c;
and call
*m_switch->doStuff();
Here, the compiler also replaces the extra pointer because it is static?
Is there any other smart way to make these keys?
source
share