I know downcasting like this won’t work. I need a method that WILL work. Here’s my problem: I’ve got several different derived classes all from a base class. My first try was to make an array of base class. The program has to select (more or less at random) different derived classes. I had tried casting from a base class to the derived class, putting it in the array of the base, but obviously that didn’t work. I was sincerely hoping for another method than simply sticking arrays of all the derived classes, because there could be quite a few derived classes. Is there any better way to do this that I’m just brainfarting on?
If y’all need code examples or more information, just let me know. It all makes sense to me, but It’s late and it may not make sense to everybody else heh.
Any help is very much appreciated, guys.
Not sure what you mean. Sounds like you store the objects by value, and you you have an array of
Base. That won’t work, because as soon as you assign a Derived, that object will be converted to a Base, and the Derived part of the object is sliced away. But i think you want to have a array of pointers to base:If you ever haved worked with pointers, you will know it’s a pain in the ass to manage them, espacially pass around and not lose them, since you will need to call delete on them to free the memory and call the destructor of the objects. You can use shared_ptr, and it will manage that for you:
Now, you can pass
bases[x]to another shared_ptr, and it will note you have got more than one reference – it will call automatically delete if the last reference to the objects go out of scope. Ideally, you would also replace the raw array by std::vector:Then you can pass the vector around, and don’t lose the size of it, and you can dynamically add items to it on demand. Get the size of the vector using
bases.size(). Read aboutshared_ptrhere.Conversion from a Base class to a Derived class should only be done when absolutely necessary. Normally, you want to use a technique called
polymorphism, which means you call a function on the base pointer, but it will actually call a function defined in the derived class, having the same signature (name and parameters are the same type) and is said tooverrideit. Read the article on wikipedia about it. If you really need to cast, you can do it like this for a raw pointer:Using dynamic_cast ensures, that when you cast to the wrong type (i.e the type you cast is not the type that was created and assigned to the base pointer), you get an exception thrown by the operator. For the shared_ptr case, there are ways too: