Sharing the Heritage (Quiz Game)

Sharing the Heritage (Quiz Game)

  • Comments 31

I was reading recent discussion threads and found something interesting that someone introduced as a question, but instead of start developing the whole story from here, I’ll just challenge you with two different quiz games.

Quiz 1
  1. #include <iostream>
  2.  
  3. class Foo {
  4. public:
  5.     virtual void DoStuff()=0;
  6. };
  7.  
  8. class Bar : public Foo {
  9. public:
  10.     virtual void DoStuff(int a)=0;
  11. };
  12.  
  13. class Baz : public Bar {
  14. public:
  15.     void DoStuff(int a) override
  16.     {
  17.         std::cout << "Baz::DoStuff(int)";
  18.     }
  19.  
  20.     void DoStuff() override
  21.     {
  22.         std::cout << "Baz::DoStuff()";
  23.     }
  24. };
  25.  
  26. int main() {
  27.     Baz baz;
  28.     Bar *pBar = &baz;
  29.  
  30.     pBar->DoStuff();
  31. }

Without using Visual Studio or your building tool of preference, just your knowledge, if we tried to run this code, what is expected to see in the console? Why?

Now let’s make a little variation and substitute the method getting no arguments for one getting char, as follows:

Quiz 2
  1. #include <iostream>
  2.  
  3. class Foo {
  4. public:
  5.     virtual void DoStuff(char a)=0;
  6. };
  7.  
  8. class Bar : public Foo {
  9. public:
  10.     virtual void DoStuff(int a)=0;
  11. };
  12.  
  13. class Baz : public Bar {
  14. public:
  15.     void DoStuff(int a) override
  16.     {
  17.         std::cout << "Baz::DoStuff(int)";
  18.     }
  19.  
  20.     void DoStuff(char a) override
  21.     {
  22.         std::cout << "Baz::DoStuff(char)";
  23.     }
  24. };
  25.  
  26. int main() {
  27.     Baz baz;
  28.     Bar *pBar = &baz;
  29.  
  30.     pBar->DoStuff('a');
  31. }

If we ran this new version, provided that it compiles with no errors, what is expected to be seen in the output console? Why?

 

Solutions are explained in this sequel.

  • Overloading would be less confusing if it were called Obfuscation instead.

    My guess (since there seems to be a few guesses going on)

    Quiz 1:  "Baz::DoStuff()"

    Quiz 2:  "Baz::DoStuff(char)"

    This appears to be the intention, and it is the pure virtual nature of the methods of both FOO and BAR which causes the child classes to be called.

    This  is assuming there isn't a compiler error when BAR doesn't override DoStuff() in Quiz 1, or DoStuff(char) in Quiz 2.

Page 3 of 3 (31 items) 123