I was watching a video on udemy and the instructor checks to see if two strings are equal by using ==
In java they use a .equals method to compare two objects such as strings for equality,when we use == we are checking if both objects in memory point to the same address,
is this different in c++? why didn't he use input.compare(password) == 1 instead of input == password?
if anyone could clear that up for me would be great thanks
when we use == we are checking if both objects in memory point to the same address
No, you are checking if both strings are the same.
why didn't he use input.compare(password) == 1 instead of input == password?
While both methods, the operator== is also a method, do basically the same thing the compare() method returns an int that indicates if the string is less than, greater than, or equal to the string in the parameter. The operator returns a bool telling if the two strings are or are not equal to each other.
yes, that is correct, you cannot overload java which is one of the top couple of flaws in the language (it makes hard core math development almost impossible).
And yes the C++ string class overloads == (and many other) operators to make it very easy to use.
In C++, == is used for logical equivalence: true if the operands have equivalent logical state.
Equality of addresses is used to check two variables refer to the same object.
#include <iostream>
#include <iomanip>
template < typename T > void foo( const T& a, const T& b )
{
constbool equal = a == b ; // true if the value of a is equal to the value of b
// a and b need not be the same integer
constbool same_object = std::addressof(a) == std::addressof(b) ;
// true if both a and b refer to the same object
std::cout << std::boolalpha << "equal? " << equal << " same object? " << same_object << '\n' ;
}
int main()
{
int a = 5, b = 5, c = 6 ;
foo( a, a ) ; // equal? true same object? true
foo( a, b ) ; // equal? true same object? false
foo( a, c ) ; // equal? false same object? false
std::string s = "abcd", t = "abcd", u = "abcde" ;
foo( s, s ) ; // equal? true same object? true
foo( s, t ) ; // equal? true same object? false
foo( s, u ) ; // equal? false same object? false
}
Pointer-disadvantaged languages (which also tend to be value-semantics-disadvantaged) do not have this luxury of consistency; in those == for some types means logical equivalence, and for some other types means same object identity.
> so if we write a class and make it equalityComparable we would have to overload the == operator for that class?
Yes, keeping these things in mind: for two objects a and b belonging to our class
1. a == b should be a predicate - the result of the expression can be considered to be either true or false
2. a == b should result in true if and only if a and b have logically equivalent values.
3. Principle of least surprise dictates that we should also provide for a != b which should be the negation of a == b