Tag Archives: and rule of three

overloading, functions vs. methods, and rule of three

As we progress through the semester, and a fast approaching third test we find ourselves focusing on overloading, functions(symmetric operations) vs methods(asymmetric), and the rule of three.

    when overloading functions or methods in C++ there are several values that can be overridden. for functions we have: the types of the arguments and if the function is not an operator then we can also override on the number of arguments. Likewise with methods we can override on the type of the arguments and the const-ness of the method, if the method happens to not be an operator then we can also override on the number of arguments as well.

   In designing a class one of the questions that should be asked is whether the function could/should belong to the class which members it would need to take as an argument. To answer this question we can look at the constructor and if it is not marked explicit(as such allowing implicit conversion from the type of argument it accepts) then we should allow the function to remain outside of the scope of the class, this way we can have the implicit conversion for its arguments happen on either side. In addition to the last mentioned sided-ness argument one should also consider if the left hand side of the function needs to be of another class (for example the input/output streams) if this is the case then we again want to keep the function outside the scope of any class as we cant modify the stream class directly, so we let the globally scoped function do the work for us. Otherwise it might be appropriate to declare the function as a method instead.

 The rule of three was another topic covered and it quite simply says that if we need to override any of the destructor, copy constructor, or the copy assignment operations then we will likely need to override the other two of the ones mentioned above. To do this without repeating code we could create helper methods or we could define the copy constructor in terms of assignment or the assignment in terms of the copy constructor, the latter if probably more favorable as it leads to a three line solution involving calling swap.