Created
April 27, 2015 08:39
-
-
Save waleedsamy/8cf457eefe3eacf5a2d1 to your computer and use it in GitHub Desktop.
c++ opp , virtual keyword
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// virtual is all about binding , early binding in compliation so it will determine abject and so method to call | |
// as reference is or late binding shen method is virtual so binding determine in run time dynamically | |
// according to actual type of object and sall it's method | |
// depend on http://stackoverflow.com/questions/2391679/why-do-we-need-virtual-methods-in-c | |
#include <iostream> | |
using namespace std; | |
class Animal | |
{ | |
public: | |
void eat() { cout << "I'm eating generic food.\n"; } | |
virtual void like() { cout << "I'm like generic food.\n"; } | |
}; | |
class Cat : public Animal | |
{ | |
public: | |
void eat() { cout << "I'm eating a rat.\n"; } | |
void like() { cout << "I'm like eating rats.\n"; } | |
}; | |
void func(Animal *xyz) { xyz->eat(); xyz->like(); } | |
int main(){ | |
Animal *animal = new Animal; | |
Cat *cat = new Cat; | |
animal->eat(); // outputs: "I'm eating generic food." | |
cat->eat(); // outputs: "I'm eating a rat." | |
func(animal); | |
func(cat); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment