Reputation: 163
There is a problem that confuses me
I created a new variable
Foo *a=new Foo();
Then I declared an Instance variable
Foo b;
Now I want to convert the new variable to the instance variable, so I did
b.setValue0(a->getValue0());
b.setValue1(a->getValue1());
b.setValue2(a->getValue2());
Is there an easier faster way to do this?
Upvotes: 0
Views: 57
Reputation: 544
You can use copy constructor with a reference to a const parameter. It is const to guarantee that the copy constructor doesn't change it.
class Foo{
public:
. . .
// copy constructor
Foo(const Foo &b)
{
value0 = b.value0;
value1 = b.value1;
}
}
//=== file main_program.cpp ====================================
. . .
Foo fooObj; // calls default constructor
Foo anotherFooObj = fooObj; // calls copy constructor.
Upvotes: 0
Reputation: 1
"Is there an easier faster way to do this?"
You can declare an assignment operator for Foo
Foo& operator=(const Foo&);
Thus you can write
b = *a;
The other option is to provide a copy constructor
Foo(const Foo&);
This allows to initialize b
directly
Foo b(*a);
You should note that the compiler will automatically generate these operations for you, unless you declare any of these your own, or declare special constructors with paraneters.
Upvotes: 1
Reputation: 114461
You can use the copy constructor:
Foo b(*a);
assuming of course that copying the object is permitted.
Upvotes: 3