Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast a parent class as the child class

Tags:

c++

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.

like image 664
Mykroft Avatar asked Nov 03 '10 17:11

Mykroft


People also ask

Can you cast a parent class to child in Java?

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.

Can a child class access parent class?

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.

How do you call the method of parent class in a child?

Using Classname: Parent's class methods can be called by using the Parent classname. method inside the overridden method.

Can you use parent class variables child class?

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.


2 Answers

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     } } 
like image 74
fredoverflow Avatar answered Oct 04 '22 03:10

fredoverflow


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

like image 21
parasrish Avatar answered Oct 04 '22 04:10

parasrish