1

I have a hierarchy such as:

Element
|_Resitance
|_DC Voltage Source
|_AC Voltage Source
|_AC Current Source
|_DC Current Source
|_DynamicElement
|  |_Inductor
|  |_Capacitor
|_SwitchingDevices
|  |_Switch
|  |_Diode
.
.
.

As my input can be any a list of those, they are all inserted in a std::vector<Element*>. The problem is that Diode, Switch and the Voltage sources have a ID member that I have to access.

I want to be able to run a *(*Element).ID or something like this, when I'm sure that the Element is a subclass with such member.

I really don't want to include ID member in the Element class because this is something that is going to happen a lot an the class would have a lot of inappropriate member.

  • So you want to [*downcast*](https://www.bogotobogo.com/cplusplus/upcasting_downcasting.php) the `Element*` to e.g. a `Switch*`? – Some programmer dude Feb 07 '19 at 12:23
  • I was not familiar with this term and, for what I read, yes. I could create a new pointer with the new class and destroy said pointer afterwards. – Luiz Felipe Feb 07 '19 at 12:32

1 Answers1

0

Add virtual destructor to base class and use dynamic_cast<> to derived class to access its members. dynamic_cast by reference will throw exception if object is not an instance of the type you cast to and dynamic_cast by pointer will return nullptr in same case.

Example:

class Element
{
    ...
    virtual ~Element() = default;
};

...

Element * el = new Diode();
Diode * d = dynamic_cast<Diode *>(el);
if (d) {
// ok, this is diode
}
user2807083
  • 2,962
  • 4
  • 29
  • 37
  • Does this delete ```el```(why do you need the destructor?)? I need not to intervene in the order of the vector, I have to access the member without changing where ```el``` is saved. – Luiz Felipe Feb 07 '19 at 12:31
  • No, this doesn't delete `el`, its just create pointer of `Diode *` type to the same instance. – user2807083 Feb 07 '19 at 12:34
  • In that case, why the virtual destructor is necessary? – Luiz Felipe Feb 07 '19 at 12:35
  • You can use `dynamic_cast` only with classes which has virtual methods table, so such class must contain at least one virtual method, e.g. virtual destructor. – user2807083 Feb 07 '19 at 12:35
  • In my case I have a lot of virtual methods, so I could use without the destructor, is that right? – Luiz Felipe Feb 07 '19 at 12:37
  • You can read more about virtual destructor and why it should be used here https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – user2807083 Feb 07 '19 at 12:37
  • 1
    If your derived classes has additional data members you should use virtual destructor to avoid memory leaks. – user2807083 Feb 07 '19 at 12:37
  • This was really helpful because I needed to use it and had no idea! Thanks! – Luiz Felipe Feb 07 '19 at 12:40