How to call child method from a parent pointer in

2020-08-10 08:03发布

问题:

I have a base class and a child class extending it. The child class has its own method inside that the parent class does not have. That is, declaring it as virtual in the base class is not really an option.

class A {
  public:
    virtual void helloWorld();
};

class B : public A {
  public:
    virtual void helloWorld();
    void myNewMethod();
};

Then, in my implementation, I have a pointer to A and I constructed it as B:

// somewhere in a .cpp file
A* x;
x = new B();
x->myNewMethod(); // doesn't work

My current solution is to cast it:

((B *)x)->myNewMethod();

My question is, is there a cleaner way of doing this, or is casting the way to go?

回答1:

My question is, is there a cleaner way of doing this, or is casting the way to go?

A run-time cast seems to be OK in this case. However, rather than C-style casts, you should use dynamic_cast<> (in case you are not sure whether x actually points to an object of type of B):

B* pB = dynamic_cast<B*>(x); // This will return nullptr if x does not point
                             // to an object of type B
if (pB != nullptr)
{
    pB->myNewMethod();
}

On the other hand, if you are sure that x points to an object of type B, then you should use static_cast<>:

B* pB = static_cast<B*>(x);
pB->myNewMethod();


回答2:

A does not define any method called myNewMethod(), hence it can't invoke it.

Even though I normally strongly discourage from casting, here indeed casting is the only way.



回答3:

Well, you'll have to cast but you can make the code look cleaner/more readable by hiding the ugly casting syntax in a function.

B* B_static_cast(A* item)
{
     return static_cast<B*>(item);
}

A* item = new B();
B_static_cast(item)->funtion_in_B();