CPP Module 05 #
Here I will just write down a few tips and notes for myself to remember in the future about this project.
Key takeaways:
- Creating custom exceptions
- Overloading
++and--operators - Overloading the
std::cout <<operator
Custom Exceptions #
- Use
structinstead ofclass. When defining an exception, usestructinstead ofclass. They are essentially the same thing, but with classes, everything is private by default, while with structs everything is public by default. Using thestructkeyword, you can cut off having to have an exctra line just forpublic:in your exception. Shorter code! - You can also omit the
virtualandoverridekeywords (technically), even though this is not recommended. Since the base class’es “what” function is already virtual, overriding it will automatically cause our custom what function to be virtual as well. When omitting theoverridekeyword, everything will still work, but compiler will not catch certain errors as easily. - When using
structinstead of a class for your exception, you can also not specify the inheritance type, since with structs it will be public by defauly, as for with classes it will be private by default.
So writing either of these two achieves the same thing, even though the first one is the recommended approach:
class GradeTooHighException : public std::exception
{
public:
virtual const char* what() const noexcept override
{
return "Grade too high";
}
};
or
struct GradeTooHighException : std::exception
{
const char* what() const noexcept
{
return "Grade is too high";
}
};
Overloading ++ and -- operators
#
For this there are actually two operators you need to overload for each of them. For when the ++ is before the object, and for when it is after it.
MyClass& operator++(); // prefix form (++ before the object)
MyClass operator++(int); // postfix form (++ after the object)