What's the difference between a derived object and a base object in c++?

前端 未结 10 1822
一个人的身影
一个人的身影 2021-01-01 06:23

What\'s the difference between a derived object and a base object in c++,

especially, when there is a virtual function in the class.

Does the derived object

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 06:49

    What's the difference between a derived object and a base object in c++,

    A derived object can be used in place of a base object; it has all the members of the base object, and maybe some more of its own. So, given a function taking a reference (or pointer) to the base class:

    void Function(Base &);
    

    You can pass a reference to an instance of the derived class:

    class Derived : public Base {};
    Derived derived;
    Function(derived);
    

    especially, when there is a virtual function in the class.

    If the derived class overrides a virtual function, then the overridden function will always be called on objects of that class, even through a reference to the base class.

    class Base
    {
    public:
        virtual void Virtual() {cout << "Base::Virtual" << endl;}
        void NonVirtual()      {cout << "Base::NonVirtual" << endl;}
    };
    
    class Derived : public Base
    {
    public:
        virtual void Virtual() {cout << "Derived::Virtual" << endl;}
        void NonVirtual()      {cout << "Derived::NonVirtual" << endl;}
    };
    
    Derived derived;
    Base &base = derived;
    
    base.Virtual();      // prints "Derived::Virtual"
    base.NonVirtual();   // prints "Base::NonVirtual"
    
    derived.Virtual();   // prints "Derived::Virtual"
    derived.NonVirtual();// prints "Derived::NonVirtual"
    

    Does the derived object maintain additional tables to hold the pointers to functions?

    Yes - both classes will contain a pointer to a table of virtual functions (known as a "vtable"), so that the correct function can be found at runtime. You can't access this directly, but it does affect the size and layout of the data in memory.

提交回复
热议问题