fork download
  1. #include <iostream>
  2.  
  3. class A{
  4. int var;
  5. virtual void foo() = 0;
  6. public:
  7. void bar();
  8. };
  9.  
  10. class B : public A{
  11. public:
  12. int var; // This is usually not a good practice (violates Liskov's principle)
  13. void foo();
  14. };
  15.  
  16. void A::bar(){
  17. std::cout << var << std::endl; // This will output an uninitialized A var!
  18. }
  19.  
  20. void B::foo(){
  21. var = 42; // B's var hides A's var so this only sets the derived one's
  22. }
  23.  
  24. void func(){
  25. B myObj;
  26. myObj.foo(); // No polymorphic behavior here, B::foo is called
  27. myObj.bar(); // the same, but A::bar is called since B doesn't define one
  28. }
  29.  
  30. class A2{
  31. virtual void foo() = 0;
  32. public:
  33. int var;
  34. void bar() {
  35. std::cout << var;
  36. }
  37. };
  38.  
  39. class B2 : public A2{
  40. public:
  41. void foo() {
  42. var = 42; // Sets the common A2::var variable
  43. };
  44. };
  45.  
  46. void func2(){
  47. B2 myObj;
  48. myObj.foo();
  49. myObj.bar();
  50. }
  51.  
  52. int main() {
  53. func();
  54. func2();
  55. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
134514939
42