Basic polymorphic pointers to base classes

孤街醉人 提交于 2019-12-22 06:34:07

问题


While I've been working in c++ for a while, I haven't had need to use polymorphic features until now, and I'm very intrigued by them.

If I have a base class ClassA and another ClassB derives from it, I understand that I can have virtual member function in ClassA that, when implemented in ClassB, will be called in a ClassB instance even if that instance is pointed at using a ClassA pointer. Without this virtual keyword, I presume the base class implementation would prevail when using a base class pointer, yet be operating on an object that was instantiated from the subclass, which seems questionable to me if in fact ClassB has its own implementation of the same function that is effectively ignored in such a case.

Is this a correct understanding of polymorphic behavior?

Now the real question is how do you refer to ClassB using a pointer to is base class. I can really only think of two ways:

  1. Create the pointer at the time of instantiation, using a function that returns a base class pointer while actually allocating memory for the subclass instead, using the subclass's constructor. (Does such a creation function have a common name?)
  2. Casting an object using static_cast and assigning it to a pointer to the base class.

Are these the two main techniques for generating base class pointers to objects of a subclass?


回答1:


The easiest way is to simply assign it, no cast necessary:

ClassA *ptrA = new ClassB;

You're correct that you need the virtual keyword to enable polymorphic behavior. Here's one way to think about it. C++ operates on the static type of an object. When you call ptrA->foo(), the type of the pointer is ClassA*. If that function is not declared virtual, then it will blindly call ClassA's version of the function. There's no other choice. But if foo() is virtual, then it knows to stop and ask, "Wait, what type am I really?" And the answer in that case is ClassB, so it will call ClassB's version.

Also note that you don't need pointers to achieve this. Another common way you'll see polymorphism in action is via a function call:

void bar(ClassA &aObj)
{
    aObj.foo();
}

// ...
ClassB bObj;
bar(bObj);


来源:https://stackoverflow.com/questions/15812517/basic-polymorphic-pointers-to-base-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!