<aside> *️⃣ Allows us to redefine/overload standard behaviour of operators such as +, -, *, ==, etc for user defined data types.
</aside>
Consider the following class:
class Complex {
private:
double real, img;
public:
Complex(){real = 0.0; img = 0.0;}
Complex(double r, double i){real = r; img = i;}
// Overload the + operator
Complex operator+ (const Complex& rhs)
};
Complex Complex::operator+(const Complex& rhs){
return Complex(real + rhs.real, img+ rhs.img);
}
const
to prevent changes to members of the objectNow we can finally do this in the main
Complex c1(3, 2), c2(1, 7);
Complex c3 = c1 + c2; // Uses the overloaded + operator
<<
to printWe can make it a friend function
class Complex{
private:
double real;
double img;
public:
Complex(){real = 0,0; img = 0,0;}
Complex(double r, double i){real = r; img = i;}
Complex operator+ (Complex& rhs);
friend ostream& operator<<(ostream& os, const Complex& x);
};
ostream& operator<<(ostream& os, const Complex& x){
os << "(" ,, x.real << ", " << x.img << ")";
return os;
}
operator <<
is not a member, so not need for Complex::
Constructor that initializes an object using another object of the same type:
ClassName(const ClassName& source);
By default, every class has a copy constructor that copies all data members
class Student{
string name;
int ID;
public:
Student(const Student& other){
name = other.name;
ID = other.ID;
}
};
When class members are pointers, especially pointing to dynamically allocated memory, there are some issues:
Bit-wise copy of an object’s members- for pointer members, this means copying the address they point to, and not the data