How can I check which derivate is it of one class and how can I work with their structure in a list

70 views Asked by At

I have the following problem and I hope the great community can help me. If I have a class one:

class one
{
private:
  int data;

public:
  one();
  void safe();
  void load();
};

And then 2 derivative classes of class one:

class two: public one
{
private:
  int data2;
public:
  two();
  safe();
  load();
};

class three: public one
{
private:
  int    data3;
  string data4;
public:
  three();
  void safe();
  void load();
};

And now I have to store data in these classes. The object of the classes are stored in a List. And one Element of these List can be in this example one object of class two or class three. Now If I have to save the content of a list in a file I need to get data of data2 or If I have the other object I need data3 and data4.

How can I check which derivate it is and how can I get the data of the objects? I mean that must be possible because they are both derivatives of one.

1

There are 1 answers

6
Steephen On

If you need a list:

std::list<one*> myList;

if you need a collection like an array

std::vector<one*> myVec;

You can see more details on how to inesrt and process data from list std::list here : http://www.cplusplus.com/reference/list/list/

For std::vector<> here : http://www.cplusplus.com/reference/vector/vector/

For your second question:

How can I check which derivate it is and how can I get the data of the objects?

Since you already created an inheritance and going to keep objects as pointers in container like std::list or std::vector, system can identify the dynamic type of the objects using polymorphism and invoke the functions depends on the type of the object. More details are available here : http://www.cplusplus.com/doc/tutorial/polymorphism/