Figure 1 shows a program
that, as of z/OS® V1R6
C/C++ compiler, would generate an exception under the IBM® object
model because the call to a member function version() on
the object _b occurs before the declaration of _b.
Figure 1. Example that highlights
sequence of statements to declare and call a virtual function
#include
class A {
public:
A(int i) : v(i) {}
virtual int version() {return 0;} 1 ;
private: int v;
};
class B:virtual public A {
public:
B(int i) : A(i) {}
};
extern B _b; 2
static int ver = _b.version(); 3
B _b(1); 4
int main() {
printf("version: %d\n", ver);
return 0;
}
Notes:
The virtual keyword tells the compiler that the
function is virtual and it can be overloaded by any derived class
of A.
A reference to externally defined _b of type
B.
The value of static global variable ver is initialized
with the value returned by member function version() called
by object _b. An exception will be raised because
the object _b is not fully constructed at the time
of the call to the member function version().
The declaration of the polymorphic object _b occurs
after its use on the previous line. This line should precede the
definition of ver to ensure that the virtual function version() is
found at run time.