Difference between revisions of "CPP/Classes/PureVirtualFunction"
From ProgrammingExamples
< CPP
(→PureVirtualFunction.cpp) |
|||
| Line 33: | Line 33: | ||
==Virtual Functions & Abstract Classes== | ==Virtual Functions & Abstract Classes== | ||
<source lang="cpp"> | <source lang="cpp"> | ||
| − | + | #include <iostream> | |
| + | |||
| + | class Vehicle | ||
{ | { | ||
| − | return | + | public: |
| + | //Here we declare a Pure Virtual Function | ||
| + | virtual void SeeMeGo()=0; | ||
| + | }; | ||
| + | |||
| + | /* Some Derived Classes */ | ||
| + | class Car : public Vehicle | ||
| + | { | ||
| + | public: | ||
| + | void SeeMeGo() | ||
| + | { | ||
| + | std:cout<<"I'm running at 50mph.\n"; | ||
| + | } | ||
| + | }; | ||
| + | |||
| + | class Bike : public Vehicle | ||
| + | { | ||
| + | public: | ||
| + | void SeeMeGo() | ||
| + | { | ||
| + | std:cout<<"I'm whooshing at 80mph.\n"; | ||
| + | } | ||
| + | }; | ||
| + | |||
| + | class Truck : public Vehicle | ||
| + | { | ||
| + | public: | ||
| + | void SeeMeGo() | ||
| + | { | ||
| + | std:cout<<"I'm crawling at 20mph.\n"; | ||
| + | } | ||
| + | }; | ||
| + | |||
| + | int main(int argc, char *argv[]) | ||
| + | { | ||
| + | //Create a Pointer to Abstract Class Vehicle | ||
| + | Vehicle *myVehicle; | ||
| + | |||
| + | //Create Some Objects | ||
| + | Car myCar; | ||
| + | Bike myBike; | ||
| + | Truck myTruck; | ||
| + | |||
| + | //Call Functions | ||
| + | myVehicle = &myCar; | ||
| + | myVehicle->SeeMeGo(); | ||
| + | |||
| + | myVehicle = &myBike; | ||
| + | myVehicle->SeeMeGo(); | ||
| + | |||
| + | myVehicle = &myTruck; | ||
| + | myVehicle->SeeMeGo(); | ||
| + | |||
| + | return 1; | ||
} | } | ||
</source> | </source> | ||
Revision as of 09:28, 23 June 2010
PureVirtualFunction.cpp
#include <iostream> #include <limits> class Point { public: Point(const double xin, const double yin, const double zin) : x(xin), y(yin), z(zin) {} double x,y,z; virtual void Output() = 0; }; class DerivedClass { void Output() { std::cout << "Point Class." << std::endl; } }; int main(int argc, char *argv[]) { return 0; }
Virtual Functions & Abstract Classes
#include <iostream> class Vehicle { public: //Here we declare a Pure Virtual Function virtual void SeeMeGo()=0; }; /* Some Derived Classes */ class Car : public Vehicle { public: void SeeMeGo() { std:cout<<"I'm running at 50mph.\n"; } }; class Bike : public Vehicle { public: void SeeMeGo() { std:cout<<"I'm whooshing at 80mph.\n"; } }; class Truck : public Vehicle { public: void SeeMeGo() { std:cout<<"I'm crawling at 20mph.\n"; } }; int main(int argc, char *argv[]) { //Create a Pointer to Abstract Class Vehicle Vehicle *myVehicle; //Create Some Objects Car myCar; Bike myBike; Truck myTruck; //Call Functions myVehicle = &myCar; myVehicle->SeeMeGo(); myVehicle = &myBike; myVehicle->SeeMeGo(); myVehicle = &myTruck; myVehicle->SeeMeGo(); return 1; }