Hi All,
In below code when class a object is assigned to class b by returning object through factory method i observed assignment is not happening properly and after assignment still class b's object points to NULL object only.
*cobj=rhs;//it gives NULL object
However below statement works perfectly when b object cobj is directly assigned inside assignment operator .
cobj=a::fact("a11")//it works fine
can anybody let me know what is wrong with assignment approach ? I know there are other way as well (setter method) but i am curious
to know in this circumstances how assignment is taken care.
#include <iostream>
using namespace std;
class a {
int a1;
public:
a(int _a1 = 0) : a1(_a1) {}
void virtual showname()=0;
static a* fact(string name);
};
class a11:public a
{
public:
void showname()
{
cout<<"john";
}
};
class a12:public a
{
public:
void showname()
{
cout<<"jack";
}
};
a* a::fact(string name)
{
if(name=="a11")
{
return new a11();
}
if(name=="a12")
{
return new a12();
}
return NULL;
}
class b {
public:
const b& operator=(const a& rhs);
private:
a* cobj;
public:
void fun(){cobj->showname();}
};
const b& b::operator=(const a& rhs) {
if(&rhs!=cobj)
{
delete cobj;
*cobj=rhs;//it gives NULL object
//cobj=a::fact("a11");it works fine
}
return *this;
}
int main() {
a* aobj = a::fact("a11");
b* bobj = new b;
*bobj = *aobj;
bobj->fun();
return 0;
}