I have a base class line which has a child class arc (note that additional classes will inherit from line)… I need to store a list, or vector of line objects that may be a line or an arc. arc has an additional property that line does not. So as I’m working with my lists, or vector of line objects, how do I determine whether the object is a line or an arc?
I have prepared a small sample program and put in comments with pseudo-code a sample of what I would be trying to accomplish. Is this even possible?
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
struct point
{
double x;
double y;
};
class line
{
public:
point start;
point end;
};
class arc: public line
{
public:
point center;
};
int main( int argc, char* argv[] )
{
vector<line*> a;
a.push_back( new line );
a.push_back( new arc );
for( vector<line*>::iterator i = a.begin(); i < a.end(); i++ )
{
(*i)->start.x = 10;
(*i)->start.y = 11;
(*i)->end.x = 101;
(*i)->end.y = 102;
//if( type of (*i) is arc )
//{
// (i)->center.x = 111;
// (i)->center.y = 112;
// }
}
return 0;
}
In your loop, try this:
Sid is also right…use virtual functions for this instead. Using dynamic_cast for simple cases such as this is generally considered poor style.