Foo::Foo(Bar* bar, int a) //Foo takes a reference of type Bar
{
}
I need to use 'bar' object in a member function in class Foo.
Foo::do_something()
{
Do something with 'bar'
}
Do I need to create a reference in Foo and make it equal to bar? How can I do it?
>>If I use bar directly in do_something function then i get error saying bar is undefined.
All I want to do is use 'bar' in do_something function.
Do I need to overload = operator or write copy constructor in Class Bar?
What to use?
By default, both copy-constructor and copy-assignment operator perform member-wise copying, thereby leaving the left-hand side operand (the calling class) in the exact same state as the right-hand side operand. When pointers are involved, a member-wise copy will leave the left-hand side operand's pointer member pointing to the same location as the member pointer of the right-hand side operand. When pointers are not involved, the member-wise copies are sufficient. Note that if you have to overload one of either copy-assignment operator, copy-constructor, or destructor, you have to overload all three. This is known as the "Rule of Three".
However, if all you want to do is use "bar" in "Foo::do_something( )" and nothing else, then just call "Foo::do_something( )" in the constructor's body and pass "bar" to it. For instance:
1 2 3 4 5 6 7 8 9 10 11 12
struct Foo
{
Foo(Bar *bar, int a)
{
this->do_something(bar); // "this->" is optional.
}
void do_something(Bar *Param_)
{
// ...
}
};
It's perfectly safe to invoke member-functions with a constructor body.