first Thanks to everyone here ,
I just want to know what the meaning and why we use this symbol '&' when we we need to compare 2 things in classes by using the overloading operators in classes, and also what the benefits of declaring the 'displayMydog' and not using it because instead I used the << ostream to ouput the last 3 lines .
thanks
// main.cpp
#include "Dog.h"
int main ()
{
Dog myDog("Spot",5.5,3);
Dog yourDog("Jack",4.4,3);
{
if (myDog >= 2)
cout <<"the dog is at least 2 years old." <<endl;
else
cout <<"the dog is less than 2 years old." <<endl;
}
{
if (yourDog < myDog)
cout <<"Your dog weighs less than my dog."<<endl;
else
cout <<"Your dog does not weigh than my dog."<<endl;
}
{
if (myDog == yourDog)
cout <<"they have the same name."<<endl;
else
cout <<"they do not have the same name."<<endl;
}
return 0;
}
//Dog.h
#include<iostream>
#include<string>
usingnamespace std;
class Dog
{
private:
string _name;
float _weight;
int _age;
public:
Dog(string name,float weight,int age)
{
_name = name;
_weight = weight;
_age = age ;
}
//==================
~Dog()
{}
//================
void displayDog()
{cout <<"NAME : "<<endl;
cout <<"WEIGHT : " <<endl;
cout <<"AGE : " <<endl;
}
booloperator >=( int num)
{
if( _age >= num)
returntrue;
elsereturnfalse;
}
//===========================
booloperator < (Dog & dog)
{
if (_weight < dog._weight)
returntrue;
elsereturnfalse;
}
//=============================
booloperator ==(Dog & dog)
{
if (_name == dog._name)
returntrue;
elsereturnfalse ;
}
//=======================================
friend ostream & operator << (ostream & stream, Dog & dog)
{
stream<<"NAME : "<< dog._name<<endl <<"WEIGHT : "<<dog._weight <<endl<<"AGE : "<<dog._name<<endl;
return stream;
}
};
Dog & dog passes a reference to a Dog object. That is, it doesn't copy the object to be compared, it passes the location in memory to an already existing Dog object. Otherwise a temporary duplicate Dog object would be created, which doesn't need to happen. For the sake of argument, pretend your Dog class took up megabytes of memory because it stores a ton of information. We don't want to copy that around willy nilly, that would wreak havoc on our system. So you pass a reference to prevent from copying.
As for you displayDog vs. operator<< overload question.
It would make sense to have one or the other if you can guarantee that you will only ever want to use it in one way.
However, if you can't guarantee that, it would make more sense to have operator<< call displayDog to prevent code duplication. For example:
thanks a lot ,
about the last point you explaind I agree with you , but in the homework page, the teacher want us to declar displayDog without any passed argument , so that;s why I get confused