Home > Article > Backend Development > Summary of C++ Review Key Points 11 - Polymorphism (2)
1 Can virtual functions be called in the constructor to achieve polymorphism?
1) When is the VPTR pointer in the object initialized?
When the object is created, the VPTR pointer is initialized by the compiler
The pointer of VPTR is finalized only after the construction of the object is completely completed
The pointer of the parent class object VPTR points to the parent class virtual function table
The VPTR of the subclass object points to the subclass virtual function table
class Parent { public: Parent(int a=0)//执行时此时的调用的print函数仍然是父类的函数(此时会将vptr指针指向父类的虚函数表) { this->a = a; print(); } virtual void print() { cout<<"我是爹"<<endl; } private: int a; }; class Child : public Parent { public: Child(int a = 0, int b=0):Parent(a)//先执行父类构造器,执行完之后返回子类(vprt指针指回子类虚函数表) { this->b = b; print(); } virtual void print() { cout<<"我是儿子"<<endl; } private: int b; }; void HowToPlay(Parent *base) { base->print(); //有多态发生 //2 动手脚 } void main() { Child c1; //定义一个子类对象 ,在这个过程中,在父类构造函数中调用虚函数print 能发生多态吗? system("pause"); return ; }
Second parent class pointer When the step size is inconsistent with the step size of the subclass pointer
class Parent { public: Parent(int a=0) { this->a = a; } virtual void print() { cout<<"我是爹"<<endl; } private: int a; }; //成功 ,一次偶然的成功 ,必然的失败更可怕 class Child : public Parent { public: /* Child(int a = 0, int b=0):Parent(a) { this->b = b; print(); } */ Child(int b = 0):Parent(0) { //this->b = b; } virtual void print() { cout<<"我是儿子"<<endl; } private: //int b; }; void HowToPlay(Parent *base) { base->print(); //有多态发生 //2 动手脚 } void main() { Child c1; //定义一个子类对象 ,在这个过程中,在父类构造函数中调用虚函数print 能发生多态吗? //c1.print(); Parent *pP = NULL; Child *pC = NULL; Child array[] = {Child(1), Child(2), Child(3)}; pP = array; pC = array; pP->print(); pC->print(); //多态发生 pP++; pC++; pP->print(); pC->print(); //多态发生 pP++; pC++; pP->print(); pC->print(); //多态发生 cout<<"hello..."<<endl; system("pause"); return ; }
The above is the summary of C++ review points 11-Polymorphism (2), For more related content, please pay attention to the PHP Chinese website (www.php.cn)!