Add qq1126137994 WeChat: liu1126137994 to learn more techniques together! ! !
Question 1: Can constructors and destructors be virtual functions?
Answer:
1. The constructor cannot become a virtual function
because the virtual function table pointer is correctly initialized after the execution of the constructor is completed.
2. The destructor can become a virtual function
. It is recommended to design the destructor as a virtual function when designing a class, especially when there are inherited classes.
Question 2: Does polymorphic behavior occur in constructors and destructors?
Answers:
1. Polymorphic behavior is not possible
in constructors: because the virtual function table pointer is not properly initialized before the execution of the constructor ends
2. Polymorphic behavior is not possible in the destructor:
because the virtual function table pointer has been destroyed when the destructor is executed
If a virtual function is called in the constructor and destructor, then only the version of the virtual function defined in the current class is called
See the example program below:
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base()" << endl;
func();//在构造函数中不会发生多态行为,虽然func()函数为虚函数
//但是编译器不会去动态绑定,会直接调用本类中的成员函数
}
virtual void func()
{
cout << "Base::func()" << endl;
}
virtual ~Base()
{
func(); //在析构函数中也不会发生多态行为,当编译器发现析构函数中有虚函数时
//编译器不会实现动态绑定的行为,而是直接调用本类中的成员函数
cout << "~Base()" << endl;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived()" << endl;
func();//在构造函数中不会发生多态行为,虽然func()函数为虚函数
//但是编译器不会去动态绑定,会直接调用本类中的成员函数
}
virtual void func()
{
cout << "Derived::func()" << endl;
}
~Derived()
{
func();//在析构函数中也不会发生多态行为,当编译器发现析构函数中有虚函数时
//编译器不会实现动态绑定的行为,而是直接调用本类中的成员函数
cout << "~Derived()" << endl;
}
};
int main()
{
Base* p = new Derived();
// ...
delete p;
return 0;
}
The running result is:
Base()
Base::func()
Derived()
Derived::func()
Derived::func()
~Derived()
Base::func()
~Base()
From the running result, we can also easily See that the above conclusions are correct!