一. 编译器对C++的多态是通过在Class里面插入一个vptr指针,同时生成一个virtual table, 让vptr指向这个virtual table来实现的,那么什么样的Class才有必要设置vptr指针呢?如下图所示:
下面分6种情况讨论
(1)有虚函数的基类
class A { public: virtual void foo() {} protected: int i; };
(2) 没有虚函数的基类
class A { public: void foo() {} protected: int i; };
(3) 虚继承,基类有vptr
class Base { public: virtual ~Base() {} virtual void foo() {} virtual void bar() {} protected: int i; }; class Derived : public virtual Base { public: ~Derived() {} void bar() {} protected: int j; };
(4)非虚继承,基类没有vptr,派生类没有虚函数
class Base { public: ~Base() {} void foo() {} void bar() {} protected: int i; }; class Derived : public Base { public: ~Derived() {} void bar() {} protected: int j; };
(5)非虚继承,基类没有vptr,派生类有虚函数
class Base { public: ~Base() {} void foo() {} void bar() {} protected: int i; }; class Derived : public Base { public: ~Derived() {} virtual void bar() {} protected: int j; };
(6) 非虚继承,基类有vptr
class Base1 { public: virtual ~Base1() {} virtual void foo() {} virtual Base1 *clone() const {} protected: int i; }; class Base2 { public: virtual ~Base2() {} virtual void bar() {} virtual Base2 *clone() const {} protected: int j; }; class Derived : public Base1, public Base2 { public: virtual ~Derived() {} virtual Derived *clone() const {} protected: int k; };