S
subramanian100in
In the following program, I have used operator==() as member function
for learning purpose only.
consider the following program:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test(int arg);
Test(const Test &rhs);
Test& operator=(const Test &rhs);
inline int value() const;
inline bool operator==(const Test &rhs) const;
private:
int val;
};
Test::Test(int arg) : val(arg)
{
}
Test::Test(const Test &rhs) : val(rhs.val)
{
}
Test &Test:perator=(const Test &rhs)
{
if (this != &rhs)
val = rhs.val;
return *this;
}
inline int Test::value() const
{
return val;
}
inline bool Test:perator==(const Test &rhs) const
{
return value() == rhs.value();
}
int main()
{
vector<Test> c1;
c1.push_back(Test(10));
vector<Test> c2;
c2.push_back(Test(10));
if (c1 == c2)
cout << "c1 equals c2" << endl;
else
cout << "not equal" << endl;
return EXIT_SUCCESS;
}
I compiled this program with g++ -std=c++98 -pedantic -Wall -Wextra.
It produced the output
c1 equals c2
However if I remove 'const' from the comparison member function
bool Test:perator==(const Test &rhs) const
ie if I have
bool Test:perator==(const Test &rhs)
Then I get compilation error for the line
if (c1 == c2)
What is the reason for the compilation error when Test:perator==()
is made non-const ?
If I remove operation==() from Test class and make it a free function,
then also the compilation error is gone and the program works fine as
it should be.
Kindly clarify.
Thanks
V.Subramanian
for learning purpose only.
consider the following program:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test(int arg);
Test(const Test &rhs);
Test& operator=(const Test &rhs);
inline int value() const;
inline bool operator==(const Test &rhs) const;
private:
int val;
};
Test::Test(int arg) : val(arg)
{
}
Test::Test(const Test &rhs) : val(rhs.val)
{
}
Test &Test:perator=(const Test &rhs)
{
if (this != &rhs)
val = rhs.val;
return *this;
}
inline int Test::value() const
{
return val;
}
inline bool Test:perator==(const Test &rhs) const
{
return value() == rhs.value();
}
int main()
{
vector<Test> c1;
c1.push_back(Test(10));
vector<Test> c2;
c2.push_back(Test(10));
if (c1 == c2)
cout << "c1 equals c2" << endl;
else
cout << "not equal" << endl;
return EXIT_SUCCESS;
}
I compiled this program with g++ -std=c++98 -pedantic -Wall -Wextra.
It produced the output
c1 equals c2
However if I remove 'const' from the comparison member function
bool Test:perator==(const Test &rhs) const
ie if I have
bool Test:perator==(const Test &rhs)
Then I get compilation error for the line
if (c1 == c2)
What is the reason for the compilation error when Test:perator==()
is made non-const ?
If I remove operation==() from Test class and make it a free function,
then also the compilation error is gone and the program works fine as
it should be.
Kindly clarify.
Thanks
V.Subramanian