I was trying to create an instance of an object with private constructor. Is this method correct?
#include <iostream>
using namespace std;
class A{
int y;
A(int y=2):y(y){};
public:
A(const A &obj){
cout<<"copy Cotr is called"<<endl;
this->y=obj.y;
}
int* addr(){
int *a=&y;
return a;
}
static A create(int y1=2){
class A a(y1);
cout<<&a<<endl;
return a;
}
void print(){
cout<<y<<endl;
}
};
int main(){
A o1=A::create(1);
A o2=A::create(3);
cout<<&o1<<" "<<&o2<<endl;
return 0;
}
The output is:
0x7ffd20d2f280
0x7ffd20d2f284
0x7ffd20d2f280 0x7ffd20d2f284
In the above code, I fail to understand few points:
create()
returns a value, so during assignment which take place inA o1=A::create(1);
, copy constructor should be called but it isn't. why?- Is this some undefined behavior as the address of the object created in
create()
and inmain()
are same and the object increate()
is local and goes out of scope after the function ends.
Aucun commentaire:
Enregistrer un commentaire