member access operators

Aug 4, 2016 at 3:28pm
Hi,

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 (.)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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;
}	
Last edited on Aug 4, 2016 at 3:29pm
Aug 4, 2016 at 3:39pm
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.
Last edited on Aug 4, 2016 at 3:40pm
Aug 4, 2016 at 7:39pm
Aha...I think I get it! Thx

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.

1
2
Object object;
object.method();

object not being pointed at

1
2
Wood * nPtr = new Wood;
nPtr->method();

pointer access
Last edited on Aug 4, 2016 at 7:40pm
Aug 4, 2016 at 7:52pm
Some lamo attempts to replicate the "non-syntactic"

a->b == (a*).b

Last edited on Aug 4, 2016 at 7:54pm
Topic archived. No new replies allowed.