So, the destructor is called twice if my object isn’t passed by the reference.
But when i pass it by reference everything is ok.
<!-- language: lang-cpp -->
ostream& operator<<(ostream& os,Counter_naslednik_1 &object){
cout<<endl<<object.date<<endl;
return os;
}
//-----------------
void main(){
Counter_naslednik_1 new_object;
cout<<new_object;
}
Why is the destructor called twice? And why should I pass my object by reference when passing it as a parameter to an overloaded operator?
It’s called twice because when you pass by value you are actually making a copy of your object, so there are two objects to destroy.
With respect to your second question, once again, passing the new object by reference avoids making a new copy of your data. This is more efficient and avoids unexpected behaviour, in case you have not designed your copy constructor.