C++ examples for Class:Virtual Function
Access specifiers and virtual functions
#include <iostream> #include <string> #include <iostream> class Pool{/*from w w w . j av a 2 s. c o m*/ protected: double length {1.0}; double width {1.0}; double height {1.0}; public: Pool(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv} {} // Function to show the volume of an object void showVolume() const { std::cout << "Pool usable volume is " << volume() << std::endl; } // Function to calculate the volume of a Pool object virtual double volume() const { return length*width*height; } }; 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} {} protected: // Function to calculate volume of a ToughPack allowing 15% for packing double volume() const override { return 0.85*length*width*height; } }; int main() { Pool pool {20.0, 30.0, 40.0}; 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.showVolume(); // Volume of Pool hardcase.showVolume(); // Volume of ToughPack carton.showVolume(); // Volume of Carton // Now using a base pointer... Pool* pPool {&pool}; // Points to type Pool std::cout << "\npool volume through pPool is " << pPool->volume() << std::endl; pPool->showVolume(); pPool = &hardcase; // Points to type ToughPack std::cout << "hardcase volume through pPool is " << pPool->volume() << std::endl; pPool->showVolume(); pPool = &carton; // Points to type Carton std::cout << "carton volume through pPool is " << pPool->volume() << std::endl; pPool->showVolume(); }