chesschi
chesschi

Reputation: 708

Passing pointer to object in constructor

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!

Upvotes: 2

Views: 14748

Answers (1)

merlin2011
merlin2011

Reputation: 75545

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;
}

Upvotes: 6

Related Questions