vendredi 22 mai 2015

What() method for std::exception isn't acting virtual?

So in the reference manual, the what() method is described as virtual, but it doesn't seem to be acting that way. (I am compiling with g++ and the c++11 flag)

#include <stdio.h> //printf
#include <iostream> //cout
#include <stdexcept>// std::invalid_argument
using namespace std;

void fn(){
    throw runtime_error("wowwowo");
}

int main(){
    try {fn(); }
    catch(exception a) {cout << a.what() << endl;}
    return 0;
}

The output for this is "std::exception", as opposed to the error message, "wowwowo". However, if I change the catch type to runtime_error, it behaves as expected. I have some code where I would like to catch exceptions that may or may not be runtime_errors, and I suppose I could have multiple catch blocks, but I'm curious as to why the code behaves as it does. Here's the code that prints out the error message:

#include <stdio.h> //printf
#include <iostream> //cout
#include <stdexcept>// std::invalid_argument
using namespace std;

void fn(){
    throw runtime_error("wowwowo");
}

int main(){
    try {fn(); }
    catch(runtime_error a) {cout << a.what() << endl;}
    return 0;
} 

Aucun commentaire:

Enregistrer un commentaire