Sign in to follow this  
RyanZec

initialization of class problem

Recommended Posts

I have a class, player, that hold the address of another class, party. The thing is that I try to set the reference to NULL by default in the constructor but I get this error: c:\documents and settings\ryan\desktop\my projects\party_test\party_test\player.cpp(8) : error C2354: 'ncharacters::player::_current_party' : initialization of reference member requires a temporary variable Is their a way to set a reference to a class as NULL or something else so that it does not hold something random in it.

Share this post


Link to post
Share on other sites
Quote:
Original post by RyanZec
Is their a way to set a reference to a class as NULL or something else so that it does not hold something random in it.
Nope, that's the point in references - there's no such thing as a null reference (Well there is, but you shouldn't get one under normal circumstances). If you want to point something to "null", you should either use a pointer, or create a null player that you can test against (They might have an empty name or something)

Share this post


Link to post
Share on other sites
Cool, I set it to a pointer. Is their something I can set a reference to or should I just make this a pointer since this pointer may or may not point to anything and can change an unlimited amount of times?

Share this post


Link to post
Share on other sites
References are initilised once, to point at another object. You can't re-assign a reference. If you need to change what the reference points to, you need to use a pointer. That's the reason you don't get null-references; If you had one, you wouldn't be able to change it to point at anything.

If you have:

int a = 42;
int b = 100;
int& ref = a;


Then doing ref = b; will change the value to the value of b, meaning a will take on the value 100.

Share this post


Link to post
Share on other sites
Ok, That does make sense to me now that I see it, thanks. Still alittle rusty after take about 1 - 1 1/2 years break from doing any C++ programming but it is now coming back.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this