C++ examples for Class:Virtual Function
Using an abstract class
#include <iostream> #include <string> class Pool{/*from w ww. ja v a 2 s .c om*/ protected: double length {1.0}; double width {1.0}; double height {1.0}; Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv}{} public: virtual double volume() const = 0; // Function to calculate the volume }; using std::string; class Carton : public Pool { private: string material; public: // Constructor explicitly calling the base constructor Carton(double lv, double wv, double hv, string str = "material") : Pool {lv, wv, hv} { material = str; } // Function to calculate the volume of a Carton object double volume() const override { double vol {(length - 0.5)*(width - 0.5)*(height - 0.5)}; return vol > 0.0 ? vol : 0.0; } }; class ToughPack : public Pool{ public: // Constructor ToughPack(double lv, double wv, double hv) : Pool {lv, wv, hv} {} // Function to calculate volume of a ToughPack allowing 15% for packing double volume() const override { return 0.85*length*width*height; } }; int main() { ToughPack hardcase {20.0, 30.0, 40.0}; // A derived pool - same size Carton carton {20.0, 30.0, 40.0, "plastic"}; // A different derived pool Pool*pPool {&hardcase}; std::cout << "hardcase volume is " << pPool->volume() << std::endl; pPool = &carton; std::cout << "carton volume is " << pPool->volume() << std::endl; }