A class in C++ is the building block that leads to Object-Oriented programming. Class is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class.
The overloading of operators is a polymorphism that occurs at compile-time. A special meaning can be given to an existing operator in C++ without changing its meaning.
Syntax:
class sampleClass { public: returntype operator operatoToBeOverloaded ( [arguments required] ) { //sampleCodeHere } };
Except for a few that cannot be overloaded, almost all operators can be overloaded. These operators are as follows:
- scope resolution operator (::)
- sizeof operator
- typeid operator
- The conditional operator (?:)
== is a comparison operator that returns a true or false Boolean value. It checks if the two operands on the operator’s left and right sides are equal.
Consider a class Car having the following data members:
class Class{ private: string name; int cost; };
In this class, we can use the == operator to determine whether the two worker’s objects are equivalent.
bool operator == (const Car &c) { if (name == c.name && cost == c.cost) return true; return false; }
// C++ Program to overload == operator #include<iostream> #include<string> using namespace std;
class Car{
private :
string name;
int cost;
public :
Car(string n, int c){
name=n;
cost=c;
}
bool operator == ( const Car &c){
if (name == c.name && cost == c.cost)
return true ;
return false ;
}
}; int main(){
Car car1 ( "Santro" ,500000);
Car car2 ( "Safari" ,1000000);
if (car1 == car2)
cout<< "Equivalent" <<endl;
else
cout<< "Not Equivalent" <<endl;
} |
Not Equivalent