Please explain to me why the destructor gets called on the "strand" object after its assigned with "tari" members. this question has been puzzling me and I haven't been able to move on from it as it gives me the wrong answer of 5 at the end instead of 10 when i try to add the contents of the "jesu" objects because the destructor gets called and any operation done on strand object becomes obsolete
#include <iostream>
#include <iomanip>
using namespace std;
class Bheki
{
private:
string name;
int sam;
double *jesu = nullptr;
public:
Bheki(){}
void Hvo()
{
jesu = new double(5);
}
double* getJesu() const
{
return jesu;
}
void setName(string Gama){name = Gama;}
void setSam(int ram){sam=ram;}
string getName()const{
return name;
}
int getSam()const{
return sam;
}
~Bheki(){
delete jesu;
jesu = nullptr;
}
const Bheki operator=(const Bheki &);
const Bheki operator+(const Bheki &);
};
const Bheki Bheki::operator+(const Bheki &ned)
{
Bheki temp;
temp.sam = sam + ned.sam;
temp.jesu = new double();
*temp.jesu = (*jesu) + (*ned.jesu);
cout<<*temp.jesu<<endl;
return temp;
}
const Bheki Bheki::operator =(const Bheki &pop)
{
if(this != &pop)
{
this->name = pop.name;
this->sam =pop.sam;
this->jesu = new double{};
*this->jesu = *pop.jesu;
}
return *this;
}
int main()
{
Bheki *tari = new Bheki();
tari->Hvo();
tari->setName("jece");
tari->setSam(6969);
cout<<tari->getName()<<endl;
Bheki *strand = new Bheki;
*strand = *tari;
cout<<strand->getName()<<endl;
strand->setName("Kumkani");
cout<<tari->getName()<<endl;
*strand->getJesu()=20.325;
cout<<strand->getJesu()<<endl;
cout<<tari->getJesu()<<endl;
*strand->getJesu() = 32;
cout<<*tari->getJesu()<<endl;
strand->setSam(884);
tari-> setSam(7);
cout<<*tari->getJesu()<<endl;
*strand->getJesu() = 5;
*tari->getJesu() = 5;
Bheki *balo = new Bheki;
*balo = *strand + *tari;
cout<<*balo->getJesu()<<endl;
cout<<balo->getSam()<<endl;
// delete tari;
// delete balo;
// delete strand;
return 0;
}
I compare my code with another post I found posted by @Serge Rogatch who said that it does not get called at assignment but mine does get called which completely contradicts each other
#include <iostream>
#include <string>
class Test
{
std::string _name;
public:
Test(std::string name ="") : _name(name) { }
~Test()
{
std::cout << "Destructor " << _name << std::endl;
}
Test& operator=(const Test& fellow)
{
// avoid changing the name of the object
std::cout << "Assignment operator "
<< _name << "=" << fellow._name << std::endl;
return *this;
}
};
int main()
{
Test t1, t2("t2");
t1 = t2;
return 0;
}