Skip to content

Instantly share code, notes, and snippets.

@waleedsamy
Created April 27, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waleedsamy/8cf457eefe3eacf5a2d1 to your computer and use it in GitHub Desktop.
Save waleedsamy/8cf457eefe3eacf5a2d1 to your computer and use it in GitHub Desktop.
c++ opp , virtual keyword
// 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