简体   繁体   中英

How can I use child class methods not defined in a parent class from a parent class pointer?

I currently have multiple child classes inheriting off of a single parent class. These child classes have radically different member variables and methods. I am trying to upcast instances of these classes and, at the same time, I need to be able to find out which child class each object belongs to and use its unique methods.

Currently, my attempts look something like this:

class Parent {
public:
int childNo;
}

class Child1: public Parent {
public:
Child1() {
int childNo = 1;
}
void radicallyDiffentMethod1(){}
}

class Child2: public Parent {
public:
Child2() {
int childNo = 2;
}
void radicallyDiffentMethod2(){}
}

void useChild(Parent* child)
if (child -> childNo == 1){
child -> radicallyDifferntMethod1();
} else {
child -> radicallyDifferentMethod2();
}

Child1* C1 = new Child1;
Child2* c2 = new Child2;

useChild(C1);
useChild(C2);

However, this does not work as the Parent class does not define radicallyDifferentMethod1 or radicalllyDifferentMethod2. How would I go about doing this?

If you want to cast through an inheritance hierarchy, you can static_cast the Parent pointer to a child pointer, like so

void useChild(Parent* child) 
{
  if (child -> childNo == 1)
  {
    static_cast<Child1*>(child) -> radicallyDiffentMethod1();
  } 
  else 
  {
    static_cast<Child2*>(child) -> radicallyDifferentMethod2();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM