Wednesday, 23 January 2019

Describe how to implement virtual functions using function pointers

Describe how to implement virtual functions using function pointers?

Answer:


The code for the base class would look like:
class base {
public:
void (*funct_ptr)(void); // Pointer to a function
void base_version_of_funct(void) {...};
base(void) {
funct_ptr = base_version_of_funct;
}
void call_funct(void) {
(*funct_ptr)();
}
};
class derived {
public:
void derived_version_of_funct(void) {...}
derived(void) {
// ... base gets constructed first
// Now override the function pointer
funct_ptr = derived_version_of_funct;
}
};

No comments:

Post a Comment