Why dynamic binding - a problem of static binding
#include #include using namespace std; // class declaration for the base class class One { protected: double a; public: One(double = 2); // constructor double f1(double); double f2(double); };// class implementation for One One::One(double val) // constructor { a = val; } double One::f1(double num) { return (num / 2); } double One::f2(double num) { return (pow(f1(num), 2)); // square the result of f1( ) } class Two : public One { public: double f1(double); // this overrides class One's f1( ) // f2( ) function unchanged! }; double Two::f1(double num) { return (num / 3); } int main() { One object_1; Two object_2; // call f2( ) using a base class object call cout << "The computed value using a base class object call is " << object_1.f2(12) << endl; // call f2( ) using a derived class object call cout << "The computed value using a derived class object call is " << object_2.f2(12) << endl; return 0; }
The computed value using a base class object call is 36
The computed value using a derived class object call is 36
If you modify the definition of class One,which is adding a keyword virtual, as follows.
class One { protected: double a; public: One(double = 2); // constructor virtual double f1(double); // a member function double f2(double); // another member function };
The computed value using a base class object call is 36
The computed value using a derived class object call is 16