More C++ Concepts: - Operator Overloading - Friend Function - This Operator - Inline Function
More C++ Concepts: - Operator Overloading - Friend Function - This Operator - Inline Function
Operator overloading
Programmer can use some operator symbols to define special member functions of a class
Provides convenient notations for object behaviors
We can make object operation look like individual int variable operation, using operator functions Complex a,b,c; c = a + b;
3
Examples:
operator+ operator-
operator*
operator/ --- operator is a function
void CStr::cat(char *s) { int n; char *pTemp; n=strlen(s); if (n==0) return; pTemp=new char[n+nLength+1]; if (pData) strcpy(pTemp,pData);
new_string.cat(str2.get_Data());
//concatenate the second operand onto the //end of new_string
return new_string;
//call copy constructor to create a copy of //the return value new_string
}
new_string str1 strcat(str1,str2) strlen(str1) strlen(str1)+strlen(str2)
name
Copy constructor
John Johnson
Temporary CStr object
7
c = a+b;
c = a.operator+ (b);
1. The function can access the private part of the class definition 2. The function is in the scope of the class 3. The function must be invoked on an object
Which of these are true about the different functions?
12
What is Friend?
Friend declarations introduce extra coupling between classes
Once an object is declared as a friend, it has access to all non-public members as if they were public
Access is unidirectional
Friends can have access to everything, which defeats data hiding, so use them carefully Friends have permission to change the internal state from outside the class. Always recommend use member functions instead of friends to change state
14
Assignment Operator
Assignment between objects of the same type is always supported
the compiler supplies a hidden assignment function if you dont write your own one same problem as with the copy constructor - the member by member copying Syntax:
Argument type - a reference to a CStr object (since it is const, the function cannot modify it)
CStr& CStr::operator=(const CStr &source){ //... Do the copying return *this; Assignment function is called as a }
str1=str2;
str1.operator=(str2)
this pData
nLength
CStr object (*this)
17
ostream& operator<<(ostream &os, const Date &d) { os<<d.month<</<<d.day<</<<d.year; return os; cout ---- object of ostream }
cout<< d1; //overloaded operator
18
istream& operator>> (istream &in, Date &d) { char mmddyy[9]; in >> mmddyy; // check if valid data entered if (d.set(mmddyy)) return in;
Inline functions
An inline function is one in which the function code replaces the function call directly. Inline class member functions
if they are defined as part of the class definition, implicit if they are defined outside of the class definition, explicit, I.e.using the keyword, inline.
In both cases, the compiler will insert the code of the functions get_Data() and getlength() instead of generating calls to these functions
21