It's been a while since I have had to write C++ code and I'm feeling kind of stupid. I've written code that is similar to, but is not exactly, the code below:
class Parent { ... }; class Child : public Parent { ... }; class Factory { static Parent GetThing() { Child c; return c; } }; int main() { Parent p = Factory::GetThing(); Child c1 = p; // Fails with "Cannot convert 'Parent' to 'Child'" Child c2 = (Child)p; // Fails with "Could not find a match for 'TCardReadMessage::TCardReadMessage(TCageMessage)'" }
I know this is supposed to be simple but I'm not sure what I'm doing wrong.
Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child's properties. However, we can forcefully cast a parent to a child which is known as downcasting.
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
Using Classname: Parent's class methods can be called by using the Parent classname. method inside the overridden method.
The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.
A Parent
object returned by value cannot possibly contain any Child
information. You have to work with pointers, preferably smart pointers, so you don't have to clean up after yourself:
#include <memory> class Factory { // ... public: static std::unique_ptr<Parent> GetThing() { return std::make_unique<Child>(); } }; int main() { std::unique_ptr<Parent> p = Factory::GetThing(); if (Child* c = dynamic_cast<Child*>(p.get())) { // do Child specific stuff } }
Refer to the code snippet below:
Child* c = dynamic_cast<Child*>(parentObject);
where, parentObject
is of type Parent*
Ensure, that the "parentObject" is actually of "Child" type, otherwise undefined-behavior.
Refer for More Info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With