Casting base class pointer to child class to extend functionality?

I have a question, maybe stupid.
Is it safe to assume that i can call a child class method on a base class (having casted it's pointer), if my child class only adds methods and not members?
No, it's not safe. You'll probably get a runtime error
Ah, this was a stupid question then :P. I was thinking, since my child class would have the same layout in memory if i had no new members, i could have called a method of the cild class on the base class without risk.
I was asking this because i'm using a library, for which i have added extension methods to some of it's classes. The problem is that every time the library is released, i have to put back my additions into it. I was thinking, if i can create child classes with the new methods, and use them on the base classes returned from the library (by casting the pointers), it would remove the need to modify each new version of the library.
The problem is when it tries to do a function lookup for the object. Even though you've casted it to the child class, it was still created as the base class and so its functions are those of the base class. To get round this i would create a copy constructor for the child class that takes the base class as an argument. The good as well is that you can use the child class object for functions that need the base class.
Something like:

1
2
3
4
ChildClass(const BaseClass &bc)
{
//copy required members
}
Last edited on
Topic archived. No new replies allowed.