Overloading isn't really that complex. Basically, you create one or more member functions (methods) or functions that have the same name, but a different parameter list. When you call the function, the compiler looks for the function that has the parameters that match the ones you pass into it. Example:
Code:
#include <string>
#include <iostream>
int myFunction(char *);
int myFunction(string &);
int myFunction(char *){ return 1; }
int myFunction(string &){ return 2; }
int main(int argc, char **argv){
string myString = "my string";
return myFunction(myString); // myFunction(string &) is called
} // End main()
It is important to note, that the return type is NOT a factor in which function is called. Example:
Code:
#include <string>
#include <iostream>
int myFunction(char *);
char myFunction(string &);
int myFunction(char *){ return 1; }
char myFunction(string &){ return 2; }
int main(int argc, char **argv){
string myString = "my string";
return myFunction(myString); // myFunction(string &) is called
} // End main()
And this will throw an error and not compile (because it cannot figure out which one is which):
Code:
#include <string>
#include <iostream>
int myFunction(string &);
char myFunction(string &);
int myFunction(string &){ return 1; }
char myFunction(string &){ return 2; }
int main(int argc, char **argv){
string myString = "my string";
return myFunction(myString);
} // End main()
With that in mind, the operator=() is no different than any other function. So, you would have the following functions for the scenerios in your earlier post:
Code:
// object = object (use 'this' to refer to self; and return '*this' -- it returns to itself)
inline BST<ElementType> & BST<ElementType>::operator=(BST<ElementType> & other_bst);
// object = different object (use 'this' to refer to self; and return '*this' -- it returns to itself)
inline BST<ElementType> & BST<ElementType>::operator=(vector<int> &);
inline BST<ElementType> & BST<ElementType>::operator=(string &);
inline BST<ElementType> & BST<ElementType>::operator=(unsigned int);
// Above parameters for example purposes only.
In addition, when using operator=() in the instance you are always going to 'return *this;'. This may seem weird, but it isn't really. The operator=() is always going to operate on the righthand side of the expression and assign a value to the lefthand side (namely, the class itself). So, it is VERY unlikely that you will ever overload an operator=() in a class and return anything except *this.
Bookmarks