Bug Buster 004: Can You Bust the Bug?

This is our fourth bug for you to track down and eradicate. You can find the previous bug here! How good are you at finding problems in code? The following is a code snippet compiles fine. Unfortunately, it is believed to have a problem. Does it? Take a look at the code listing and see if you can determine which of the statements that follows it is correct. One of the options is correct, while the others are not.

Can you find any issues without looking at the choices?

Bug Buster #4 

Here is the Bug Buster:

Code:

#include <iostream>
using std::cout;
using std::endl;

struct B {
  int virtual f() { return 1; }
};

struct D : public B {
  int virtual f() { return 2; }
};

void main() {
	B* pd2 = new B;
	D* pb2 = dynamic_cast<D*>(pd2);

	cout << "result is " << (pb2 ? pb2->f() : 0) << endl;

	char x;
	x = 1;
}

Your choices:

The listing will throw an exception when trying to access pb2->f().
The listing will throw a runtime exception when pb2 is declared.
The listing seems to work; however, the result is 2 will be displayed.
The listing seems to work; however, the result is 1 will be displayed.
The listing seems to work; however, the result is 0 will be displayed.
The listing seems to work; however, a memory address will be displayed.

How quickly can you find the answer? Feel free to post a comment on how quick you were! We will be posting additional snippets over the coming weeks with additional coding issues for you to bust.  You can click to the next page to find the solution.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read