假设我有两个c++类:
class A
{
public:
A() { fn(); }
virtual void fn() { _n = 1; }
int getn() { return _n; }
protected:
int _n;
};
class B : public A
{
public:
B() : A() {}
virtual void fn() { _n = 2; }
};
如果我写下面的代码:
int main()
{
B b;
int n = b.getn();
}
有人可能认为n被设为2。
结果是n被设为1。为什么?
Firstly,Object is created and then we assign it 's address to pointers.Constructors are called at the time of object creation and used to initializ the value of data members. Pointer to object comes into scenario after object creation. Thats why, C++ do not allows us to make constructors as virtual .
.another reason is that, There is nothing like pointer to constructor , which can point to virtual constructor,because one of the property of virtual function is that it can be used by pointers only.
虚函数用于动态赋值,因为构造函数是静态的,所以我们不能将它们设为虚函数。