最近从水木C++版看到了这个问题,什么情况下纯虚函数会被调用?
这个链接解释的比较清楚,http://www.artima.com/cppsource/pure_virtual.html
下面是一个demo,在基类构造函数中调用纯虚函数,
>> cat pure1.C
#include <iostream>
using namespace std;
class B {
public:
B()
{
func();
}
void virtual func() = 0;
};
class D : public B {
public:
void func() {
cout << " I am in D " << endl;
}
};
int main()
{
D *pd = new D();
}
Solaris Sun CC,
>> CC pure1.C
"pure1.C", line 8: Warning: Attempt to call a pure virtual function B::func() will always fail.
1 Warning(s) detected.
>> ./a.out
Pure virtual function called
Abort(coredump)
Linux g++
>> g++ pure1.C
pure1.C: In constructor `B::B()':
pure1.C:8: error: abstract virtual `virtual void B::func()' called from constructor
在基类构造函数中间接调用纯虚函数,
>> cat pure.C
#include <iostream>
using namespace std;
class B {
public:
B()
{
fun();
}
void fun()
{
func();
}
void virtual func() = 0;
};
class D : public B {
public:
void func() {
cout << " I am in D " << endl;
}
};
int main()
{
D *pd = new D();
}
Linux g++,
>> g++ pure.C
>> ./a.out
pure virtual method called
terminate called without an active exception
Abort(coredump)
Solaris Sun CC,
>> CC pure.C
>> ./a.out
Pure virtual function called
Abort(coredump)