You have a lot of options. Here are 5.
Solution 1: Pass a reference of B to A instead of a pointer.
Although it is possible to have a reference to a NULL object. It's really hard to do, and you don't need to check for it.
class A
{
B &b;
public:
A (B& b_) : b(b_)
{
}
int getB()
{
return b.getB();
}
};
Solution 2: Don't sacrifice the relationship design of your classes with this, but it may be applicable.
Have class A derived from B. Then you can simply call getB().
Solution 3: Perhaps you shouldn't use a pointer at all and simply make B a member of A.
class A
{
B b;
public:
int getB()
{
return b.getB();
}
};
Solution 4: Assert right away to avoid later checks
class A
{
B *b;
public:
A (B* pb) : b(pb)
{
assert(pb != NULL);
}
int getB()
{
return b->getB();
}
};
Solution 5: Have a default B that you use
class A
{
B *pb;
B defaultB;
public:
A () : pb(&defaultB)
{
}
void setB(B* pb_)
{
if(pb != NULL)
pb = pb_;
}
int getB()
{
return pb->getB();
}
};