CPP Module 05

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 struct instead of class. When defining an exception, use struct instead of class. They are essentially the same thing, but with classes, everything is private by default, while with structs everything is public by default. Using the struct keyword, you can cut off having to have an exctra line just for public: in your exception. Shorter code!
  • You can also omit the virtual and override keywords (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 the override keyword, everything will still work, but compiler will not catch certain errors as easily.
  • When using struct instead 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)