code_junkie

What are the dangers of making a method virtual?

Nov 11th, 2011
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.65 KB | None | 0 0
  1. class Base {
  2. public Base() {
  3. InitializeComponent();
  4. }
  5. protected virtual void InitializeComponent() {
  6. ...
  7. }
  8. }
  9.  
  10. class Derived : Base {
  11. private Button button1;
  12. public Derived() : base() {
  13. button1 = new Button();
  14. }
  15. protected override void InitializeComponent() {
  16. button1.Text = "I'm gonna throw a null reference exception"
  17. }
  18. }
  19.  
  20. class foo {
  21. public:
  22. foo();
  23. ~foo() { Cleanup() };
  24. virtual void Cleanup();
  25. }
  26.  
  27. class bar : public foo {
  28. public:
  29. bar()
  30. :foo() {};
  31. ~bar();
  32. virtual void Cleanup()
  33. {
  34. foo::Cleanup();
  35.  
  36. // Do some special bar() related cleanup now...
  37. }
  38. }
Add Comment
Please, Sign In to add comment