Created
January 10, 2011 23:04
-
-
Save Keruspe/773661 to your computer and use it in GitHub Desktop.
Simple example of "virtual" usage to explain it to beginners
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
#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