Is there any way to create a class through a function that its scope is in the outside??
To be clear i have this
1 2 3 4 5 6 7 8 9
Class A{
public:
int id;
//function clone();
};
main(){
A b;
b.clone();// i want this function to create a new object A with the same
// data member's values of b
I guess you could use the empty constructor and then manually fill in the data. Assuming a already exists:
1 2
A b;
b.id = a.id;
Or, if it's allowed, use the assignment operator: A b = a;
If you want to do it inside a function, be wary of scope problems. You'll have to create the "clone" outside the function and pass it by reference, else it's just a temporary and it disappears. Also, if class A has any private members, the function will need to be a friend of the class.
To be honest, that seems more like a poor excuse than a reason. There is no good reason not to define a copy constructor and call it. You can still wrap it in a clone() function if you want to.
class A {
public:
int id;
};
int main() {
A b;
A c;
b.id = 15;
c = b;
// c.id is 15
}
If you really want to have a clone function, it would have to use the new operator, and delete it afterwards. Another option would be to pass by reference, but that would add a parameter to the clone function (for the clone destination), and I think it is less intuitive.
class A {
public:
int id;
A *clone();
};
A *A::clone(){
A *cloned = new A();
*cloned = *this;
cout << "created a clone of " << this << " at " << cloned << endl;
return cloned;
}
int main()
{
A b,c,*d;
b.id = 15;
c = b;
d = c.clone();
// show that values are the same
cout << b.id << endl;
cout << c.id << endl;
cout << d->id << endl;
// show that addresses are different
cout << &b << endl;
cout << &c << endl;
cout << &d << endl;
cout << d << endl;
// must delete the cloned copy because we made it with new
delete d;
return 0;
}
class A
{
public:
friend A Clone();
void Print()
{
std::cout << "this->Member" << " = " << this->Member << std::endl;
}
private:
int Member;
};
A Clone()
{
A _X;
_X.Member = 10;
return(_X);
}
int main()
{
Clone().Print();
}
Additional information:
A friend function doesn't belong to a class, but is allowed to access the private members. Think of it this way: There's a tray of cakes on the counter. Only the person who baked the cakes (the class), and the baker's friends can eat the cakes. If you're not the baker, or a friend of the baker, on your bike.