Skip to content

Instantly share code, notes, and snippets.

@Keruspe
Created January 10, 2011 23:04
Show Gist options
  • Save Keruspe/773661 to your computer and use it in GitHub Desktop.
Save Keruspe/773661 to your computer and use it in GitHub Desktop.
Simple example of "virtual" usage to explain it to beginners
#include <iostream>
class Foo {
public:
Foo() {}
virtual void speak() {std::cout << "I'm foo" << std::endl;}
void talk() {std::cout << "I'm still foo" << std::endl;}
};
class Bar : public Foo {
public:
Bar() {}
void speak() {std::cout << "I'm bar" << std::endl;}
void talk() {std::cout << "I'm still bar" << std::endl;}
};
int main() {
/* With pointers */
Foo * fp = new Foo;
Bar * bp = new Bar;
Foo * fbp = new Bar;
fp->speak(); /* I'm foo */
fp->talk(); /* I'm still foo */
bp->speak(); /* I'm bar */
bp->talk(); /* I'm still bar */
fbp->speak(); /* I'm bar */
fbp->talk(); /* I'm still foo */
delete(fp);
delete(bp);
delete(fbp);
/* Without pointers */
Foo f;
Bar b;
Foo & fbr = b;
Foo fb = b;
f.speak(); /* I'm foo */
f.talk(); /* I'm still foo */
b.speak(); /* I'm bar */
b.talk(); /* I'm still bar */
fbr.speak(); /* I'm bar */
fbr.talk(); /* I'm still foo */
fb.speak(); /* I'm foo */
fb.talk(); /* I'm still foo */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment