Can a poninter of base class hold object of class derived from the derived class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sarbhatt
    New Member
    • Apr 2008
    • 2

    Can a poninter of base class hold object of class derived from the derived class

    I have a question, in multilevel inheritance:

    Class Base
    {
    };

    Class derv1:public Base
    {
    }

    Class derv2:public derv1
    {
    }

    Is ptrBase = &objderv2; valid?

    If yes, then if we have virtual method in Base class will VTABLE of granchild(derv2 ) class have function address of this virtual method?

    Thanks
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Base* ptrBase = &objDerv2; is fine. If you add a virtual method to Base, derv1 and derv2 must redefine those by the rules of virtual functions, but once that happens, the Vtable will include it.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by Laharl
      If you add a virtual method to Base, derv1 and derv2 must redefine those by the rules of virtual functions
      This only applies to pure virtual functions. Otherwise, the virtual function is inherited like any other function and its address ends up in the derived class VTBL.

      Comment

      • sarbhatt
        New Member
        • Apr 2008
        • 2

        #4
        Thanks for the reply.

        Comment

        Working...