Little gem from troll thread

Hello, I found this code in an old 2010 C++ bashing thread.
I would appreciate an explanation as to why exactly it prints what it does. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

using std::cout;
using std::string;

class A {
public:
  virtual void printMessage1() { cout << "Foo"; }
  virtual void printMessage2(string message = "C++ sucks") { cout << message; }
};

class B : public A {
public:
  virtual void printMessage1() { cout << "Bar"; }
  virtual void printMessage2(string message = "C++ rocks") { cout << message; }
};

int main() {
  A* object = new B();
  object->printMessage1();  // what gets printed?
  object->printMessage2();  // what gets printed?
  delete object;
}
BarC++ sucks
A virtual function call uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.

[ Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct  A  {
virtual  void  f(int  a  =  7);
};

struct  B  :  public  A  {
void  f(int  a);
};

void  m()  {
B*  pb  =  new  B;
A*  pa  =  pb;
pa->f(); // OK, calls pa->B::f(7)
pb->f(); // error: wrong number of arguments for B::f()
}

— end example ]
- IS (emphasis was added)


Btw, the last line of main() - delete object; - will result in undefined behaviour.
Last edited on
Thanks for your reply.

Btw, the last line of main() - delete object; - will result in undefined behaviour.

I added that line myself, thinking the OP forgot about it.
Let me guess... it has to do with A not having an explicit virtual destructor?
> it has to do with A not having an explicit virtual destructor?

Yes.
Topic archived. No new replies allowed.