Firstly, let's demonstrate a fact that virtual function must be implemented.
class A {
public:
A() { a = 0; }
virtual void a1();
int a2();
private:
int a;
};
int main() {
A a;
return 0;
}
![](http://hi.csdn.net/attachment/201111/15/0_1321344418M8FF.gif)
A strange error about construction occurs. Now, let's see the correct version.
class A {
public:
A() { a = 0; }
virtual void a1() { a = 1;}
int a2();
private:
int a;
};
int main() {
A a;
return 0;
}
It is right. By the way, you can see
the common member function could avoid implementation.
In contrast, the pure virtual function mustn't be implemented.
class A {
public:
A() { a = 0; }
virtual void a3() =0 { a = 1;}
private:
int a;
};
int main() {
return 0;
}
![](http://hi.csdn.net/attachment/201111/15/0_1321344796Z5Az.gif)
Another example:
class A {
public:
A() { a = 0; }
virtual void a3() =0;
private:
int a;
};
class B: public A {
public:
B(): A() { }
};
class C: public B {
public:
C(): B() {}
void a3() {}
};
int main() {
B b;
C c;
return 0;
}
![](http://hi.csdn.net/attachment/201111/15/0_1321345724vNHN.gif)
However, the correct should be
class A {
public:
A() { a = 0; }
virtual void a3() =0;
private:
int a;
};
class B: public A {
public:
B(): A() { }
};
class C: public B {
public:
C(): B() {}
void a3() {}
};
int main() {
// B b;
C c;
return 0;
}
From this experiment, we can see that pure virtual function doesn't necessarily be implemented in its subclass and hence its subclass is still a virtual class.