22 June 2009

Minimal Non-C++Programmer Bamboozling C++ Question

I recently read a stream of blog posts about why developers don't like C++ for general purpose programming. This post typifies much of the criticism of C++'s complexity. It includes an interview question about creating a C++ class that behaves like a class in a high level language such as Java. The author says that he uses this to weed out job applicants who haven't used C++ for real work.

It strikes me that tripping up developers with C++'s many oddnesses is much easier than that. Here is a simple question that I believe will confuse many non-C++ programmers:

What is the output of this program?


#include <string>
#include <iostream>
using namespace std;
class Parent {
public:
string func()  { return "parent"; }
virtual string vfunc() { return "parent+virtual"; }
};
class Child : public Parent {
string func()  { return "child"; }
virtual string vfunc() { return "child+virtual"; }
};
string test1(Parent parent)  {
return parent.func() + " - " +  parent.vfunc();
}
string test2(Parent& parent)  {
return parent.func() + " - " +  parent.vfunc();
}
int main() {
Child  child;
cout << "test1: " << test1(child) << endl;
cout << "test2: " << test2(child) << endl;
}

I have seen C++ interviewers ask questions like this but only show test1 then ask what  is on the stack when test1 is invoked.

No comments: