If I create an instance of obj (Wood obj) I can only access its members/vars with (.) -- cannot use (->) member access operator in this case. Conversely if I create a new object on the heap with 'new' I can access it with member access function (->), but not with (.) I can also use (->) to return the object's address calling the function.
Am I right in seeing that (->) is both a member access operator and a pointer value? Why can I access objects members with (.) but not (->)but in other circumstances access object members with (->) not (.)?
#include<iostream>
class Wood
{
private:
public:
int var1 = 35;
int var2 = 99;
int sumIt(int var1,int var2)
{ int summed = var1 + var2;
return summed;}
};
class A
{
private:
public:
int p=986;
//THIS: address of object calling this def
printAddress()
{std::cout<<this<<std::endl;}
};
int main()
{
//Wood obj;
//cout<<obj->var1;
Wood * nPtr = new Wood;
std::cout<<nPtr->var2<<std::endl;
A * nPtr2 = new A;
std::cout<<nPtr2->p<<std::endl;
std::cout<<nPtr2->printAddress();
//cout<<A.p;
return 0;
}
a->b is simply syntactic sugar - it means the same as (*a).b. It's a more easy-to-read way to access members of an object, when you have a pointer to that object.
Since the (->) only accesses an object being pointed at, it stands to reason why objects not pointed to use a different access method in this case the (.) operator.