Quote:Original post by midasmax
Correct me if I'm wrong, but I believe that:
*** Source Snippet Removed ***
and
*** Source Snippet Removed ***
are actually doing the same thing. Because the variable "var" is actually pointing to the address of the object ( of SomeClass ) in the heap. It's just that in C++, you need to specifically state that your variable is a pointer-to-address. In C#, you appear to be assigning a variable to an object, but what is actually happening is that you're assigning the variable to the *address* of that object.
Java programmers would also be familiar with this.
I've been programming C++ since I was ten years old, but it took me a while to grasp the concept of pointers.
Here's a short code sample.
CMyClass obj;obj.DoSomething();
The first line both declares a CMyClass object and initializes it. The second line calls a function on the object.
Now, using pointers things are a bit more complicated.
CMyClass* obj=NULL;obj=new CMyClass;if(obj!=NULL){ cout << "Memory allocation failed"; return;}obj->DoSomething();CMyClass obj2=*obj;delete obj;
Line 1 declares a "blank" pointer to a CMyClass object. Note that if you try to call a function or access a variable on this empty pointer, all hell will break loose and your program will most likely crash.
Line 2 creates a CMyClass object. The address of this object is stored in "obj". There are two things you need to be careful of:
1) The object creation may fail. If your CMyClass object is bigger than the available memory, "obj" will remain NULL.
2) You will need to destroy the object when you're done using it. If you don't, then you have a "memory leak" which will gradually eat up all of your memory until everything crashes.
The "if" block verifies that the memory allocation worked. If it didn't, then we quit with an error.
The next line calls a member function on the object.
The next line creates a standard C++ object, initializing it with a COPY of the object pointed to by "obj". The * is not multiplication in this case - it's used to mean "the object stored at this address". Beware that unless you have a custom "operator =" function to copy your data, any handles or other data stored in the first object will be copied exactly - once you close the handle on one object, the other handle will be useless.
The last line frees the memory associated with "obj" (automatically calling its destructor).
If you need any more details, drop me a line at "zonenbergsoftware@verizon.net" and I'll see what I can do.
hackerkey://v4sw7+8CHS$hw6+8ln6pr8O$ck4ma4+9u5Lw7VX$m0l5Ri8ONotepad++/e3+8t3b8AORTen7+9a17s0r4g8OP