Reputation: 283
#include <stdio.h>
class A {
public:
int getX() { return x; }
private:
int x;
};
class B {
public:
A& getA () {return a;}
private:
A a;
};
int main() {
B* b = new B;
if(b) {
b->getA().setX(10);
printf("\n Value is %p",&(b->getA()));
b->getA().setX(5);
}
return 0;
}
In the above code is there any problem and is there any case where getA() can return a NULL pointer or invalid pointer . If yes what is valid check for it ?
Upvotes: 1
Views: 78
Reputation: 5370
You cannot really check if references are valid or not (also they cannot be null). So when you use references keep that in mind that you make sure as long as you use them the object stays valid (e.g. as function parameters).
Returning Objects by reference can be helpful performance wise, but you can introduce bugs when e.g. you B
object gets destroyed and you have saved this A&
.
So if possible avoid returning references (except when you can make sure the object it references never gets invalid e.g. global variables) and if you have to be careful with them. They can introduce hard to find bugs.
Upvotes: 1
Reputation: 77285
A reference cannot be null. Testing or checking for null is redundant. Your compiler already does that. It will only confuse people who know the language.
(obviously this is C++, you can put any value into any memory location, but checking references for null is not going to help you if someone else is manipulating your memory.)
Upvotes: 4