exception handling and reference

N

nikola

Hi all,
If I have these two simple classes to handle matherr

class Matherr{



public:



virtual void print_err() const{

std::cerr << "Error";

}

};





class int_overflow : public Matherr{



private:



const char *op;

int a, b;



public:



int_overflow(const char *p, int a1, int a2){

op = p; a = a1; b = a2;

}



void print_err() const{

std::cerr << op << " (" << a << ", " << b << ")";

}

};


And the main()...

void main(int argc, char **argv){



try{

int i1 = add(1, 2) ;

int i2 = add(INT_MAX, -2);

int i3 = add(INT_MAX, 2); //Exception!

}



catch(Matherr &m){

m.print_err();

}

}



int add(int x, int y){



if((x > 0 && y > 0 && x > INT_MAX - y) || (x < 0 && y < 0 && x <
INT_MIN + y))

throw int_overflow("+", x, y);



return x + y;

}


Why if I catch using the reference (&m) it calls int_overflow's print_err()
and if I use it by value (m) it calls matherr's print_err()?
Thanx
 
S

Siemel Naran

nikola said:
class Matherr{
class int_overflow : public Matherr{
catch(Matherr &m){
Why if I catch using the reference (&m) it calls int_overflow's print_err()
and if I use it by value (m) it calls matherr's print_err()?

For the same reason that in

f(Matherr m);
int main() { int_overflow io; f(io); }

the system slices off the int_overflow part of io, and makes a copy of the
Matherr part only, and calls f. In this function a call to
m.virtualfunction() will call Matherr::virtualfunction().

But had you done

f(Matherr& m);

then you're passing the original io object, and a call to
m.virtualfunction() calls int_overflow::virtualfunction().

So passing and catching by reference you preserve the original type and
avoid making a copy, and passing and catching by value you slice off the
derived type and make an extra copy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top