C++
Chapter 8 - Operator Overloading
The Copy Constructor
When objects are passed by valued into a function, the object is copied in a bit wise fashion. This bit wise copy is sufficient for most objects, except for those objects which contain pointers to other objects. When an object containing a pointer is passed by value into a function, the object is copied, including the address of the pointer and the new object now resides within the scope of the function. When the new object drops out of scope, the new objects destructor is fired and the object pointer to is deleted. Thus leaving the original object pointer to "freed" memory!... CRASH!
To avoid this problem one can always pass by reference or you can create a copy constructor for the class, where by the action of copying instructs the copy constructor to allocate new memory and replicate the pointed to object.
For Example: copycon.cpp
Example Output
Constructor Copy Constructor Copy Constructor v1: 2.2,3.3,4.4 Destructor Destructor Destructor
Fundamentals of Operator Overloading
This class will focus on chapter 8. The goal in this chapter is to create a set of operators to perform operations relation to a specific class type. There are two basic types of operators, binary operators which have an L-value and a R-value. The addition, subtraction operators are examples of binary operators. Unary operator have only and L-value.
Assume we have three Vertex objects
Vertex v1( "v1", 2.2, 3.3, 4.4 );
Vertex v2( "v2", 3.3, 4.4, 5.5 );
Vertex v3( "v3", 4.4, 5.5, 6.6 );
High level programming would strive to write the following code.
v1 = v2 + v3
!v1;
Binary Operators: v1 = v2 + v3; ( Both the assignment and addition operator are binary )
Unary Operators: !v1; (The NOT operator is unary)
When creating operators for a class type, you the designer are responsible to implement the operator to provide the customary functionality. One could easily make the addition operator perform subtraction, but this is NOT customary.
When analyzing operators, a suggested approached to to create a functional views of how the operator works. This will identify which object is going into the operator function call and which is receiving the return.
For Example: x = y + z This can be written in
functional notation: x.=(y.+(z))
a = b = c Function Notation: a.=(b.=(c))
Vertex Class with Operators: opoverload.cpp
Example Output
Constructor Constructor Constructor Constructor v1:[2,3,4] v2:[3,4,5] v3:[4,5,6] Constructor v3 = v1 + v2 v1:[2,3,4] v2:[3,4,5] v3:[5,7,9] v1 not equals v3 x: y: z: v4:[1,2,3] v1:[2,3,4] v2:[3,4,5] v3:[5,7,9] v4:[1,2,3] Destructor Destructor Destructor Destructor
The Infinite Array Example: iarray.cpp
/* example output ma[0] = 0 ma[1] = 2 ma[2] = 4 ma[3] = 6 ma[4] = 8 */
04/12/00 03:51 PM