Expert C Programming

(Jeff_L) #1

Multiple inheritance seems a difficult, error-prone feature in both implementation and use. Some
people say that no convincing examples have been produced where there was no alternative design
avoiding multiple inheritance.


Overloading—Having One Name for the Same Action on Different Types


Overloading simply means reusing an existing name, but using it to operate on different types. The
name can be the name of a function, or it can be an operator symbol. Operator overloading is already
present in C in a rudimentary way. Virtually all languages over-load operators for built-in types.


double e,f,g;


int i,j,k;


...


e = f+g; / floating-point addition /


i = j+k; / integer addition /


The + operation is different in the two cases. The first will generate a floating-point add instruction,
and the second an integer add instruction. Since the same conceptual operation is being performed, the
name or operator should be the same. Since C++ allows the creation of new types, the programmer is
given the ability to overload names and operators for those new types too. Overloading allows
programmers to reuse function names and most operators, +, =, *, -, [], and (), giving them
additional meanings for user-defined class types. This is all part of the OOP philosophy of treating
objects as a composite whole.


Overloading (by definition) is always resolved at compile time. The compiler looks at the types of the
operands, and checks that it has seen a declaration of that operator for those types. In order to
conserve programmer sanity, you should only overload an operator for a similar operation; don't
overload * so that it now does division.


How C++ Does Operator Overloading


As an example, let's overload the "+" operator, and define addition for the Fruit class. First add the
prototype for the operator to the class:

Free download pdf