I am trying to pass a const reference object of class B to an object of class A. So that class A member function foo() can access member function bar() of class B. This below method works fine.
#include <iostream>
using namespace std;
class B {
public:
void bar() const { cout << "Bar"; }
};
class A {
public:
A (const B& _b) : b(_b) {}
void foo () { cout << "Foo"; b.bar(); }
private:
const B& b;
};
main()
{
B b1;
A a1(b1);
a1.foo();
}
However, instead of passing the b1 object in constructor of A, i am looking for a way to register the object b1 at a later stage. The way mentioned below has errors, but is there any way to achieve this ?
class A {
public:
A () {};
void registerB(const B& _b) { b =_b; } // Assignement not possible
void foo () { cout << "Foo "; b.bar(); }
private:
const B& b;
};
main()
{
B b1;
A a1;
// Do some work
a1.registerB(b1);
a1.foo();
}
EDIT
If the B object is not const, can it be made to work then ?
class A {
public:
A ():b(NULL) {};
void registerB(B& _b) { b =_b; } // Assignement not possible
void foo () { cout << "Foo "; b.bar(); }
private:
B& b; // Not const
};