I saw the others question on Stack Overflow but they only answered a part of it.
suppose we have a class-
class student
{
public:
string name;
student(string a)
{
name = a;
cout << "parmeteised const." << endl;
}
student(student &a)
{
name = a.name;
cout << "Copy const." << endl;
}
};
int main()
{
student a("Vyom");
student c(a);
if (a == c)
{
cout << "same";
}
return 0;
}
This does not compile and gives an error-
no operator "==" matches these operands -- operand types are: student == student
Now I know that this is wrong and I would have to overload the operator to do so.
My Doubts:
We have argument &a in the copy constructor but we input only a while making an object c.
If point 1 is true and valid then it probably means a stands for the memory location of the object.
if point 2 is true and valid then why can't I compare memory locations of a and c
(I know memory locations will be in hexadecimal but there must be a way to convert them into int and then compare).
I am beginner, please help me clarify my doubts.
We have argument &a in the copy constructor but we input only a while making an object c.
In the function student(student &a) variable 'a' is reference on a student. It is not a pointer (student* a).
You will have to implement the comparison operator == if you want to compare two student objects:
operator_comparison
You have to overload (implement) == operator for the class. Below is a sample == operator implementation for your class -
bool operator==(const student& a) const {
if (a.name == this->name) return true;
return false;
}
Now your code should look like below -
#include <iostream>
using namespace std;
class student
{
public:
string name;
student(string a)
{
name = a;
cout << "parmeteised const." << endl;
}
student(student &a)
{
name = a.name;
cout << "Copy const." << endl;
}
bool operator==(const student& a) const {
if (a.name == this->name) return true;
return false;
}
};
int main()
{
student a("Vyom");
student c(a);
if (a == c)
{
cout << "same";
}
return 0;
}
Related
So I am learning operation overloading.
I am trying to overload << to print object properties.
In my case Properties is a class that inherits the public section of the person class.
This is what i have:
class Person {
private:
string name;
int egn;
string adress;
public:
friend ostream& operator << (ostream& out, const Person& c);
}
ostream& operator << (ostream& out, const Person& c)
{
out << "Person name: " << c.name << "\n" << "Person egn: " << c.egn;
return out;
}
int main()
{
Properties* person_obj_1 = new Properties();
person_obj_1 = add_person(person_obj_1);//Add some values
cout << person_obj_1 << "\n";
}
And the output I get is 000001CE89252130. This is not what I want. I need to print the actual values of my attributes. What am I doing wrong?
What am I doing wrong?
You're printing a Properties* instead of a Person object. That is, to get your expected result you need to use cout on a Person object for which you've overloaded operator<< instead of Properties* which is a pointer.
How to implement the comparison function in this case?
void remove(const Object1 &object1) {
for(auto &object2 : objectVector) {
if(object1 == object2) {
/*....... */
}
}
}
You are asking 2 questions:
How can objects be made comparable:
By implementing operator== for the class. Be sure you override operator != then too.
As a member function:
bool Object1::operator ==(const Object1 &b) const
{
// return true if *this equals b;
}
Or as a free function:
bool operator ==(const Object1 &a, const Object1 &b)
How can objects with a given value be removed from a vector:
The easiest way is to use std::remove:
objectVector.erase(std::remove(objectVector.begin(), objectVector.end(), object1), objectVector.end());
You can remove objects also while iterating through the vector, but you have to keep in mind that the vector iterator is invalidated then. You may not further iterate on the vector then.
An object of your class can contain different types and number of members so let's say that you have a class A:
class A{
int x,
float y;
char* z;
};
And you have two instances:
A a1;
A a2;
To compare:
if(a1 == a2) // compile-time error
;// DoSomeThing
Above you get the error because the compiler doesn't know which fields will be compared against each other. The solution is to overload the equals operator "==" to work on objects of your class.
class Student{
public:
Student(std::string, int age);
std::string getName()const;
int getAge()const;
bool operator == (const Student&);
private:
std::string name;
int age;
};
Student::Student(std::string str, int x) :
name(str), age(x){
}
bool Student::operator == (const Student& rhs){
return age == rhs.age;
}
std::string Student::getName()const{
return name;
}
int Student::getAge()const{
return age;
}
int main(){
Student a("Alpha", 77);
Student b("Beta", 49);
if(a == b)
std::cout << a.getName() << " is the same age as " <<
b.getName() << std::endl;
cout << endl << endl;
return 0;
}
Now the compiler knows how to compare objects of your class and know what the equals operator compares on your ojects members.
if object is a class you can override the operator == in the class as a friend function, or you can implement your own function bool isEqual(Object1 o1, Object1 o2) { if(something) return true; return false; }
As an assignment for my programming class, I'm writing a class definition for floats and dynamic memory allocation. We are to build a class and use a test driver main program that runs it and tells us if our code is working or not. My code for the class is FAR from being done, but this issue is driving my crazy and I can't figure it out. Whenever the overloaded == operator is called, my copy constructor is also being called. My last post, I got a lot of negative comments for posting too long of code, so I'm doing my best to only post the code needed to see the issues.
Here's my specification:
#include <iostream>
#include <ctype.h>
using namespace std;
class MyFloat
{
enum {DefaultSizeTen=10};
char *Number;
int NumberOfDigits;
int MaxNumberOfDigits;
public:
~MyFloat();//destructor
MyFloat(const MyFloat & RHS);
MyFloat(); //default constructor
MyFloat(unsigned int Input); //create any length of MyFloat
int Digits();
int MaxDigits();
MyFloat operator= (const char Input[]);
int operator== (MyFloat x);
MyFloat operator+ (MyFloat x);
int operator> (MyFloat x);
int operator< (MyFloat x);
friend ostream& operator<< (ostream &Out, const MyFloat & X);
friend istream& operator>> (istream &In, MyFloat & X);
};
In the test driver, this is the function using the overloaded == operator:
void TestComparison()
{
MyFloat A, B, Sum;
cout << "\n\n== == == == == Testing \"== \" for MyFloat == == == == == \n\n";
cout << "MyFloat variables have maximum length of " << A.MaxDigits() << endl;
do
{
cout << "\nEnter A ==> ";
cin >> A;
cout << "\nEnter B ==> ";
cin >> B;
cout << "\n (A == B) is " << ((A == B) ? "TRUE " : "FALSE ") << endl;
}
while ( SpaceBarToContinue() );
}
It is at THIS LINE cout << "\n (A == B) is " << ((A == B) ? "TRUE " : "FALSE ") << ends;that I'm having my issue. Before the overloaded comparison operator is being called, the RHS is being sent into the copy constructor function, along with another variable, one that I can't figure out where its coming from (coming into the copy constructor as *this). Here's the copy constructor:
MyFloat::MyFloat(const MyFloat & RHS)
{
MaxNumberOfDigits=RHS.MaxNumberOfDigits;
NumberOfDigits=RHS.NumberOfDigits;
Number = new (nothrow) char[RHS.NumberOfDigits+1]; //+1 for overflow
if (Number != NULL)
{
for (int i=0; i<=RHS.NumberOfDigits-1; ++i)
{
Number[i]=RHS.Number[i];
}
}
else
NumberOfDigits=0;
}
I don't know if this is enough information, but I got some negative feedback for posting too long of code last time, so I trimmed this down a bunch.
Cant figure out why using overloaded comparison operator is calling a copy constructor before execution
You are passing the argument by value.
int operator== (MyFloat x);
Change it to a more idiomatic form:
Change the return type to bool.
Make the argument a const&.
Make the member function a const member function.
bool operator==(MyFloat const& x) const;
I want to make a typedef struct called pos (from position) that stores coordinates x and y. I am trying to overload some operators for this struct, but it does not compile.
typedef struct {
int x;
int y;
inline pos operator=(pos a) {
x=a.x;
y=a.y;
return a;
}
inline pos operator+(pos a) {
return {a.x+x,a.y+y};
}
inline bool operator==(pos a) {
if (a.x==x && a.y== y)
return true;
else
return false;
}
} pos;
I also wanted to know the difference between this:
inline bool operator==(pos a) {
if(a.x==x && a.y== y)
return true;
else
return false;
}
And this:
bool operator==(pos a) const {
if(a.x==x && a.y== y)
return true;
else
return false;
}
The breakdown of your declaration and its members is somewhat littered:
Remove the typedef
The typedef is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos as-written, which is core to your current compilation failure.
Change this:
typedef struct {....} pos;
To this:
struct pos { ... };
Remove extraneous inlines
You're both declaring and defining your member operators within the class definition itself. The inline keyword is not needed so long as your implementations remain in their current location (the class definition)
Return references to *this where appropriate
This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:
a = b = c;
This assigns c to b, and the resulting value b is then assigned to a. This is not equivalent to the following code, contrary to what you may think:
a = c;
b = c;
Therefore, your assignment operator should be implemented as such:
pos& operator =(const pos& a)
{
x = a.x;
y = a.y;
return *this;
}
Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)
Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:
pos& operator=(pos a) // by-value param invokes class copy-ctor
{
this->swap(a);
return *this;
}
Then a swap method is implemented:
void pos::swap(pos& obj)
{
// TODO: swap object guts with obj
}
You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.
Pass objects by const reference when appropriate
All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:
Change this:
bool operator==(pos a) const{
if(a.x==x && a.y== y)return true;
else return false;
}
To this: (also simplified)
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
No copies of anything are made, resulting in more efficient code.
Finally, in answering your question, what is the difference between a member function or operator declared as const and one that is not?
A const member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const member functions can be invoked against const objects, or const references and pointers. For example, your operator +() does not modify your local object and thus should be declared as const. Your operator =() clearly modifies the local object, and therefore the operator should not be const.
Summary
struct pos
{
int x;
int y;
// default + parameterized constructor
pos(int x=0, int y=0)
: x(x), y(y)
{
}
// assignment operator modifies object, therefore non-const
pos& operator=(const pos& a)
{
x=a.x;
y=a.y;
return *this;
}
// addop. doesn't modify object. therefore const.
pos operator+(const pos& a) const
{
return pos(a.x+x, a.y+y);
}
// equality comparison. doesn't modify object. therefore const.
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
};
EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:
a = b = c;
Is equivalent to this:
b = c;
a = b;
And that this does not always equate to this:
a = c;
b = c;
Sample code:
#include <iostream>
#include <string>
using namespace std;
struct obj
{
std::string name;
int value;
obj(const std::string& name, int value)
: name(name), value(value)
{
}
obj& operator =(const obj& o)
{
cout << name << " = " << o.name << endl;
value = (o.value+1); // note: our value is one more than the rhs.
return *this;
}
};
int main(int argc, char *argv[])
{
obj a("a", 1), b("b", 2), c("c", 3);
a = b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
a = c;
b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
return 0;
}
Output
b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3
Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.
Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.
To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.
(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)
try this:
struct Pos{
int x;
int y;
inline Pos& operator=(const Pos& other){
x=other.x;
y=other.y;
return *this;
}
inline Pos operator+(const Pos& other) const {
Pos res {x+other.x,y+other.y};
return res;
}
const inline bool operator==(const Pos& other) const {
return (x==other.x and y == other.y);
}
};
bool operator==(pos a) const{ - this method doesn't change object's elements.
bool operator==(pos a) { - it may change object's elements.
I tried creating a class with one operator bool and one operator void*, but the compiler says they are ambigous. Is there some way I can explain to the compiler what operator to use or can I not have them both?
class A {
public:
operator void*(){
cout << "operator void* is called" << endl;
return 0;
}
operator bool(){
cout << "operator bool is called" << endl;
return true;
}
};
int main()
{
A a1, a2;
if (a1 == a2){
cout << "hello";
}
}
The problem here is that you're defining operator bool but from the sounds of it what you want is operator ==. Alternatively, you can explicitly cast to void * like this:
if ((void *)a1 == (void *)a2) {
// ...
}
... but that's really bizarre. Don't do that. Instead, define your operator == like this inside class A:
bool operator==(const A& other) const {
return /* whatever */;
}
You could call the operator directly.
int main()
{
A a1, a2;
if (static_cast<bool>(a1) == static_cast<bool>(a2)){
cout << "hello";
}
}
In this case, though, it looks like you should define operator==() and not depend on conversions.