Passing pointer to object in constructor
c++, oop
Solution
Just add a `setB()` method and call it after you are done constructing both.
#include <iostream>
class B;
class A
{
public:
A(B * b) : _b(b) {}
void setB(B* b) {
this->_b = b;
}
void printB(void)
{
if (0 != _b)
{
std::cout << "B is not null" << std::endl;
}
else
{
std::cout << "B is null" << std::endl;
}
}
private:
B * _b;
};
class B
{
public:
B(A * a) : _a(a) {}
void printA(void)
{
if (0 != _a)
{
std::cout << "A is not null" << std::endl;
}
else
{
std::cout << "A is null" << std::endl;
}
}
private:
A * _a;
};
int main(int argc, char ** argv)
{
A * a = 0;
B * b = 0;
a = new A(b);
b = new B(a);
a->setB(b);
a->printB();
b->printA();
delete a;
delete b;
return 0;
}
Problem
I want to create two objects A and B and each object contains each other. ``` class B; class A { public: A(B * b) : _b(b) {} void printB(void) { if (0 != _b) { std::cout << "B is not null" << std::endl; } else { std::cout << "B is null" << std::endl; } } private: B * _b; }; class B { public: B(A * a) : _a(a) {} void printA(void) { if (0 != _a) { std::cout << "A is not null" << std::endl; } else { std::cout << "A is null" << std::endl; } } private: A * _a; }; int main(int argc, char ** argv) { A * a = 0; B * b = 0; a = new A(b); b = new B(a); a->printB(); b->printA(); delete a; delete b; return 0; } ``` As you can see object 'a' contains null pointer 'b'. What is the best way to re-write this code so that 'a' contains a reference to 'b'? (note that object 'a' and 'b' needs to use 'new') Many thanks!