I have a question about pure virtual functions. I am not clear about how it works and when we need to use pure virtual functions. This is the example that I do not understand:
file.h
class A
{
public :
A();
~A();
virtual void func1(void) = 0;
virtual UINT32 func2(void) = 0;
UINT32 initialize(void) = 0;
}
file.cpp
UINT32 A:initialize (void)
{
func1();
func2();
return (result);
}
Can anyone explain in detail what this example actually does and what the result is?
I really appreciate your help and knowledge. Thank you very much.
(Note, the declaration for
initialize()should not be virtual, and the implementation ofinitialize()should returnfunc2()probably. As this is an example, it doesn’t really matter whatinitialize()does, but it should compile correctly.)The primary purpose of virtual functions is to achieve polymorphism.
Class
Adefines two pure virtual methods, andinitializecalls them. This allows code in the program to initialize something of typeAwithout being aware of the subclass. There may be many subclasses ofA, and each may do something slightly differently withinfunc1()andfunc2(). Since the code that only knows aboutAis sometimes initializing objects of different types throughA,Acan be referred to as a polymorphic type.Results in the output:
This is an example of polymorphic behavior, because the output is different depending on if
Awas subclassed byBor byC.