Hello
In exception handling if you have a collection of exception types that are related through inheritance and the catch blocks take in a reference to the object thrown any base-class reference is able to refer to derived-class objects but if you pass it by value a base-class reference shouldn't recognize a derived-class object. But running my program I get the same results passing by value or reference.
#include <iostream>
#include <string>
usingnamespace std;
struct animal
{
private:
int lifespan;
char * diet;
public:
animal() : lifespan(0), diet(NULL) {}
void getlife(int glife) { lifespan = glife; }
void getdiet(char * gdiet)
{
diet = newchar[std::strlen(gdiet)+1];
std::strcpy(diet, gdiet);
}
void display()
{
cout << "Lifespan of the animal is " << lifespan << endl;
cout << "Diet of the animal is " << diet << endl;
}
};
struct bad1
{
void getstring1() { cout << "Life can't be less than zero.\n"; }
};
struct bad2 : public bad1
{
void getstring2() { cout << "Diet can't be nothing.\n"; }
};
int main()
{
animal pet;
int lifespan;
char diet[20];
try
{
cout << "What is the lifespan of the animal? ";
cin >> lifespan;
if( lifespan < 0 )
{
throw bad1();
}
pet.getlife(lifespan);
cout << "What is the diet of the animal? ";
cin.get();
cin.getline( diet, 20 );
if( strcmp( diet, "Nothing" ) == 0 )
{
throw bad2();
}
pet.getdiet(diet);
}
catch( bad2 & b2 )
{
b2.getstring2();
}
catch( bad1 & b1 )
{
b1.getstring1();
}
return 0;
}
This work fine but when you swap bad1 catch-block with bad2 catch-block you'll continuously catch bad1 which is too be excepted but when you pass by value you get the same results
when the catch blocks are order this way I'm getting the same results.
I'm pretty sure I'm misunderstanding something here.
Sorry for the silliness of the program I was just trying to see the difference between reference vs value with exceptions since a temporary object is created either way.
Thanks for any help.
g++ ex.cpp
ex.cpp: In function ‘int main()’:
ex.cpp:66: warning: exception of type ‘bad2’ will be caught
ex.cpp:62: warning: by earlier handler for ‘bad1’