Main Content

Operator Overloading, Exceptions, Pointers, References and Templates in C++ - new examples from our courses

Archive - Originally posted on "The Horse's Mouth" - 2011-11-06 07:31:47 - Graham Ellis

I've added three new C++ examples to our library following on from last week's C++ course. Each of them is one step beyond "hello world" with regard to the particular feature it's showing, but isn't so advanced and showing so many options that it confuses the newcomer - at least that's the theory. See what you think in practise ;-)

An example in which I've redefined the operators "+" and "*" for a class, so that we can combine "mean time between failure / service" objects. And the example also overrides how the << method on an output file stream works for objects of this type so that we can output them in a default format. See [source].

How to define, throw and catch exceptions in C++. Exceptions are an excellent failsafe way of trapping problems - as opposed to checking for errors which isn't intrinsically failsafe because you need to know what all the possible errors are ahead of time. See [source].

References and Pointers can both be used to (in effect) pass data into a function / method so that it's read/write - i.e. in such a way that the original data in the calling method will be changed to reflect changes made via the passed in variable. This example shows a (default) call-by-value function which doesn't work as you would wish - it swaps over copies of variables leaving the original untouched. But it then showx how to do it with references and with pointers, and also how you can do it with a template so that my "swapper" routine used is generic across all appropriate data types. [source].