I have a Visual Studio 2008 C++ application with several types of objects that derive from a common base. For example:
class Base
{
public:
std::string Time() const { /*return formatted time*/; };
private:
SYSTEMTIME time_;
};
class Foo : public Base
{
public:
const char* FooFunc() const { return "Hello from foo!"; };
};
typedef std::vector< Base > BaseList;
class Bar : public Base
{
public:
const char* BarFunc() const { return "Hello from bar!"; };
void push_back( const Base& obj ) { list_.push_back( obj ); };
BaseList::const_iterator begin() const { return list_.begin(); };
BaseList::const_iterator end() const { return list_.end(); };
private:
BaseList list_;
};
These objects are stored in a std::vector< Base >
. I need to output the information in each of the Foo
and Bar
classes as well as information stored in the base. But, I would like to avoid RTTI.
int main( int, char** )
{
BaseList list;
Foo foo;
Bar bar;
Foo foo2;
list.push_back( foo );
list.push_back( bar );
bar.push_back( foo2 );
for( BaseList::const_iterator it = list.begin();
it != list.end();
++it )
{
printf( "%s ", it->Time() );
// print Foo information for objects of type Foo
// OR print Bar information for objects of type Bar.
// Descend in to objects of type Bar to print its children.
}
return 0;
}
In this case, the desired output would be:
11:13:05 Hello from foo!
11:22:14 Hello from bar!
11:26:04 Hello from foo!
What changes can I make to this design that would avoid using RTTI as a solution but still allow me to store objects like Foo
and Bar
with different functionality in a nested tree-like structure?
Thanks, PaulH