Is it possible to pass derived classes by reference to a function taking base class as a parameter

前端 未结 2 1970
执念已碎
执念已碎 2020-12-01 04:32

Say we have an abstract base class IBase with pure virtual methods (an interface).

Then we derive CFoo, CFoo2 from the base cl

相关标签:
2条回答
  • 2020-12-01 04:43

    Yes. You don't have to upcast your objects. All references/pointers to derived types are converted implicitly to base objects references/pointers when necessary.

    So:

    IBase* ptr = new CFoo("abc"); // good
    CFoo* ptr2 = static_cast<CFoo*>(ptr); // good
    CFoo* ptr3 = ptr; // compile error
    
    CFoo instance("abc");
    IBase& ref = instance; // good
    CFoo& ref2 = static_cast<CFoo&>(ref); // good
    CFoo& ref3 = ref; // compile error
    

    When you have to downcast you may want to consider using dynamic_cast, if your types are polymorphic.

    0 讨论(0)
  • 2020-12-01 04:46

    You can cast an object just as you can a pointer. I remember this was common when converting char to unsigned char and various other sign changing casts in days of yore.

    0 讨论(0)
提交回复
热议问题