Object Oriented Programming
Object Oriented Programming
Special cases
The assignment operator (=) may be used with every class without explicit overloading. The default behavior of the assignment operator is a member-wise assignment of the data members of the class. The address operator (&) may also be used with objects of any class without explicit overloading.It returns the address of the object in memory.
Operators in C++
C++ has a rich collection of operators most of which are common to other programming languages It is the standard arithmetic and logical operators
+ - * / % & ! >> << || && == etc
We can divide up the set of operators into unary and binary operators
A unary operator has one operand Examples
if (!x) {..} x++; --x; // unary operator !, operand x // post-fix operator ++, operand x / / pre-fix operator --, operand x
int x;
Public: add(int y) {x = y;}
void display() {cout<<x<<endl;} add operator +(add a) { add temp;
public: dist(int a,float b) { feet = a; inches = b; } void display() {cout<<feet<< <<inches<<endl;} void operator +=(dist d) { feet += d.feet; inches += d.inches; if(inches>12.0) { inches -=12.0; feet++; }};
Comparison Operator-Example
Class str{ private: char s[10]; public: str(char s1[]) { strcpy(s,s1);} void display() {cout<<s;} bool operator ==(string ss) const { return (strcmp(s,ss.s)==0)? True:false;} }; Void main() { str t = yes; str t1 = no; if(t == t1) t.display(); Else t1.display(); }
Concatenating Strings
string str;
public: string operator+(string s) { strcat(str,s) return str;}}; Void main() { string s1 = hello; String s2 = world; String s3 = s1+s2; Cout<<s3; }
Restrictions on operator overloading The precedence of an operator cannot be changed The arity of an operator cannot be changed We cannot redefine a binary operator to be unary or vice verse The associativity of an operator cannot change Whether it applies left to right or right to left