简体   繁体   中英

how to throw an exception when there is no constructor in the inherited class?

I'm not sure the question is appropriate but I'll try my best.

This is my homework problem. The homework ask me to throw an exception if two lines are parallel or equal.

The original codes are provided by my professor and my job is to modify it to make it able to throw an exception.

line.h

class RuntimeException{
 private:
 string errorMsg;
 public:
 RuntimeException(const string& err) { errorMsg = err; }
 string getMessage() const { return errorMsg; }
};

class EqualLines: public RuntimeException{
 public:
 //empty
};

class ParallelLines: public RuntimeException{
 public:
 //empty
};

class Line{
 public:
 Line(double slope, double y_intercept): a(slope), b(y_intercept) {};
 double intersect(const Line L) const throw(ParallelLines,
                    EqualLines);
 //...getter and setter
 private:
 double a;
 double b;
};

Professor told us NOT to modify the header file, only the .cpp file can be modifed.

line.cpp

double Line::intersect(const Line L) const throw(ParallelLines,
                       EqualLines){
 //below is my own code
 if ((getSlope() == L.getSlope()) && (getIntercept() != L.getIntercept())) {
 //then it is parallel, throw an exception
 }
 else if ((getSlope() == L.getSlope()) && (getIntercept() ==  L.getIntercept())) {
 //then it is equal, throw an exception
 }
 else {
    //return x coordinate of that point
    return ((L.getIntercept()-getIntercept()) / (getSlope()-L.getSlope()));
 }
 //above is my own code
}

since those two inherited classes are empty hence no constructor to initialize the errorMsg , nor I can create an object of those classes to throw exception. Any alternate solution to achieve this?

Because you have an exception specifier, you may only throw EqualLines or ParallelLines . These exception types have no default constructor (their base type's doesn't have a default constructor) and have no other constructors. The only way to construct either of these exceptions is to copy an existing one. It's impossible to throw either of those exceptions without modifying the headers or violating the standard. I would consult with the professor, it looks like a mistake to me.

In general, exception specifiers are a bad idea. See this answer . They are in fact deprecated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM