By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,234 Members | 1,889 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,234 IT Pros & Developers. It's quick & easy.

exception handling and reference

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
"nikola" <se******@here.lol> wrote in message news:PxIsc.240389
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.
Jul 22 '05 #2

P: n/a
On Tue, 25 May 2004 14:15:11 GMT, "nikola" <se******@here.lol> wrote:
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()?


When you copy a derived object into a base object, the object is
"sliced". This is why you have to use pointers or references to
achieve polymorphic behaviour. Have a read of this FAQ:

http://www.parashift.com/c++-faq-lit...semantics.html

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #3

P: n/a
thanx both :)
Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.