0

I'm using Qt Creator 3.0.1 with MinGW 4.8 32-bit as the compiler.

When I put the following code into the very top of my main() function (before Qt does all its stuff), the output I get on the console is "std::exception", not "Whoops" as I would expect:

try {
    throw std::logic_error{"Whoops"};
}
catch (std::exception ex) {
    std::cout << ex.what() << std::endl;
}

I've also tried accessing what() through a pointer:

try {
    throw std::logic_error{"Whoops"};
}
catch (std::exception ex) {
    std::exception* ex2 = &ex;
    std::cout << ex2->what() << std::endl;
}

The exact same code compiled in VS2013 outputs "Whoops" as I would expect.

std::exception::what() is virtual, so why is this happening?

Steve
  • 6,334
  • 4
  • 39
  • 67
  • 2
    See http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c. `ex` is a `std::exception`, both statically and dynamically. – chris Apr 02 '14 at 19:40

1 Answers1

1

As chris said, you're slicing the information. You can prevent this by catching a const reference instead (demo):

try {
    throw std::logic_error{"Whoops"};
} catch (const std::exception& ex) {
    std::cout << ex.what() << std::endl; // Whoops
}
Community
  • 1
  • 1
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • I just found that out after looking into the link @chris posted above. I'll accept in 7 minutes when SO lets me :) – Steve Apr 02 '14 at 19:45