Sign in to follow this  
danromeo

[.net] Help clear up a basic confusion re: C# variable declaration

Recommended Posts

Hey, thanks for reading this. Tell me if I'm wrong about this: DXCamera camera; creates a variable of class DXCamera but does not allocate any memory for DXCamera members. DXCamera camera2=new DXCamera(...initialize stuff); DOES allocate memory. SO it is my understanding (please tell me if I'm wrong) that DXCamera camera2=new DXCamera(...initialize stuff); DXCamera camera = camera2; creates a variable of DXCamera class, and then what we old C++ guys called a Pointer to that variable. Thus, any changes that occur to "camera2" will be reflected in "camera" because it simply points to "camera2"'s memory location. ??? But then, if I have DXCamera camera2=new DXCamera(...); DXCamera camera=new DXCamera(....); camera=camera2; shouldn't "camera" copy all of the members of camera2 and be its' own seperate entity? Because when I make changes to "camera2", the members of "camera" change too! Obviously I have some conceptual misunderstanding here, but the material that I've read seems to back up what I thought was correct, but obviously isn't! The only thing I can think of is that I didn't override the "=" operator for the DXCamera class. Can somebody help me straighten this out? THANKS.

Share this post


Link to post
Share on other sites
Quote:
Original post by danromeo
DXCamera camera2=new DXCamera(...);
DXCamera camera=new DXCamera(....);
camera=camera2;

shouldn't "camera" copy all of the members of camera2 and be its' own seperate entity?

Because when I make changes to "camera2", the members of "camera" change too!


Unlike C++, there is no default copy constructor in C#. You have to manually create one.

DXCamera camera2=new DXCamera(...);
DXCamera camera=new DXCamera(camera2);

However now anything that happens to camera2 will have no effect on camera. If you want to share data you could use statics or events.

Quote:

The only thing I can think of is that I didn't override the "=" operator for the DXCamera class.


I don't think you can override the = operator in C# since all classes are references and that could make it impossible to transfer references.

Share this post


Link to post
Share on other sites
You answered your own question, really.

Up to this point you are good:
DXCamera camera2=new DXCamera(...);
DXCamera camera=new DXCamera(....);

Now, here.. your essentially stomping whatever reference camera was pointing to with the camera2 reference. This isn't a 'copy' at all.
camera=camera2;

If you want to copy, use the copy constructor. Something like
DXCamera camera = new DXCamera(camera2);

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