I am developing a class that has two constructors, that will use different objects. If I instance foo with no argument I want to use object bar, if I instance by foo(val) I want to use object baz.
I am getting confused how should I implement the solution. Inheritance does not seem so logical because there are differences on the functions and variables of bar and baz.
Below I present how I was thinking, basically I was setting a variable according to the called constructor. Then on my printWrapper, I was comparing this variable to know if I call bar print or baz print. One of the errors, it is due to the fact that bar and baz only have constructors with arguments. Also what I want is when I instance foo with/without argument I do not want object bar/baz created. How would you do it?
Header foo.h
class foo {
public:
foo();
foo(int val)
private:
bool object_bar;
void printWrapper();
bar b; // instance used on constructor foo()
baz c; // instance used on constructor foo(val)
}
Header bar.h
class bar {
public:
bar(int val)
private:
bool test1;
int test2;
void print();
}
Header baz.h
class baz {
public:
baz(int val)
private:
bool test1;
int test2;
int test3;
void print();
}
Source foo.cpp
foo::foo() : b(5) {
this->object_bar = true;
}
foo::foo(int val) : c(val) {
this->object_bar = false;
}
foo::printWrapper() {
if (true == this->object_bar)
b.print();
else
c.print();
}