Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - How to call child method from a parent pointer?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...