Question

Let's say I have a base class called Animal and a class Dog that inherits from Animal.

Then I create a base class.

Animal* pAnimal = new Animal();

After that I set a bunch of data for this class.

pAnimal->SetName("SomeAnimal");

Now I want to turn this Animal class into a Dog and keep all of the data that was set on Animal. Can this be done without creating a new Dog class and essentially copying over all of the data?

Hopefully you can understand my question, I essentially want to "promote" a base class into a child class without having to copy over all of the base classes existing data. I'm not sure this is possible as I don't know any way to do that.

Was it helpful?

Solution

No. It cannot. Remember, it's not magic what's happening behind all the syntactic sugar in C++ to accomplish OOP. Member variables still occupy physical addresses in memory. Two derived classes will likely not have the same variable types and alignment in memory to even make a clean cast feasible. And once you use polymorphic function interfaces (virtual functions), the problem is only compounded by the inclusion of the mechanism that implements virtual functions (commonly, it's a vtable).

As someone else alluded to, you can derive off of a common base class and cast between derived types and have only this much be "aliased" by a different type, but all of the derived data is still as it was before (so creating a cat on top of the same memory that was a dog just moments ago is not safe).

Remember, the power in OOP isn't that you do less work by being able to access the same member variables in derived classes, it's that you can code toward interfaces and that logic is tested to work and using the same interface call on a different derived type should work the same way.

For instance, imagine we have a piece of code in a hugely complex system, and one part is to feed a pet. The trouble is that cats need to be fed differently than dogs, dogs differently than birds, birds differently than turtles, etc. With polymorphic functions, our complex system can simply say something like

animal->feed();

and let the derived classes figure out how to actually get that work done. Now our complex system doesn't need to have all of the logic for feeding billions of types of animals in the control path for feeding animals. So when you need to add a new animal type, you don't need to go hunting down all the places in your code where you need specific knowledge of the animal type to accomplish the work (feeding, cleaning, primping, entertaining, etc.). You just let the new derived animal class describe how to accomplish the behavior (again: feeding, cleaning....) and your control paths up to those functions in our complex system remain unchanged.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top