I am coming back to C++ after a long venture in Java world, and am regrasping the concept/syntax of how C++ uses pointers.
So a couple of examples.
in java
public void MyFunc(MyClass class)
{
class.DoSomething;
}
is the same as
void MyFunc (MyClass* class)
{
class->DoSomething;
}
and
public MyClass GetMyClass()
{
return class;
}
is the same as (looking at it i realize i would have to store what im returning here in a pointer so its not the same…)
MyClasss* GetMyClass()
{
return (&class); // could you say here "return <-MyClass"
}
instead maybe this is the same (it would seem this should return an object of MyClass that is located at “&MyClass”, so you would be able directly edit this object at this location from wherever this is returning to )
MyClasss GetMyClass()
{
return (&class);
}
also you can use -> to access the object stored at the address the pointer points to, can you use <- to store the address?
finally, what is the point of
void MyFunc(MyClass1 &class1, MyClass2 &class2)
vs
void MyFunc(MyClass1* class1, MyClass* class2)
is it that for the first you are passing in the data store at the address while in example 2 you are passing in the address of the data you would like to use?
A pointer is a memory address where you can find your data (which can be an object, struct or primitive type). When you say
return (&object), you’re returning a memory address – a single number (say, 1736cbfa). With that memory address, you can access individual elements of object using the -> operator. You’re not “pushing back” anything to the calling function, so you don’t need any “<-” operator. Just think of the function as returning a number, but a special kind of magic number that tells you where the data you need is, and you should be fine.Regarding your final point,
void MyFunc(MyClass * object)sends a copy of the memory address/pointer/magic number where you find the data into the function.void MyFunc(MyClass & object)basically does the same thing behind the scenes, but allows you to refer to object1 directly (as in object.element instead of object->element). This second method is preferred when you want to modify object1 inside the function since you can’t accidentally dereference a null pointer this way.