C++ converting back and forth from derived and base classes
Posted
by
user127817
on Stack Overflow
See other posts from Stack Overflow
or by user127817
Published on 2011-03-14T00:05:18Z
Indexed on
2011/03/14
0:10 UTC
Read the original article
Hit count: 248
I was wondering if there is a way in C++ to accomplish the following:
I have a base class called ResultBase
and two class that are Derived from it, Variable
and Expression
. I have a few methods that do work on vector<ResultBase>
. I want to be able to pass in vectors of Variable
and Expression
into these methods. I can achieve this by creating a vector<ResultBase>
and using static_cast
to fill it with the members from my vector of Variable/Expression. However, once the vector has run through the methods, I want to be able to get it back as the vector of Result/Expression. I'll know for sure which one I want back. static_cast won't work here as there isn't a method to reconstruct a Variable/Expression from a ResultBase
, and more importantly I wouldn't have the original properties of the Variables/Expressions
The methods modify some of the properties of the ResultBase
and I need those changes to be reflected in the original vectors. (i.e. ResultBase
has a property called IsLive
, and one of the methods will modify this property. I want this IsLive
value to be reflected in the derived class used to create the ResultBase
Whats the easiest way to accomplish this?
© Stack Overflow or respective owner