0

i am little bit confused to access the class function through pointer.
Whether
Consider the pointer variable
Class Ball
{
Void Do()
{
}
}

Void main()
{
Ball &r = *(new Ball );
}
Can i access via
r.Do();
r->Do();
Which way is correct and please explain me why it is like that ?

2
Contributors
1
Reply
3
Views
8 Years
Discussion Span
Last Post by macobex
0

I think it is more advisable to instantiate an object using this syntax:
Ball *r = new Ball;

if you will follow the syntax that i've said, you can access member functions and variables using the following syntax:

(*r).Do();
or
r -> Do();

either of the 2 is correct.

The first syntax (*r).Do();
- *r is pertaining to the Ball object that the pointer 'r' is pointing to.
- Don't forget to enclose *r in parenthesis.

The second syntax r -> Do();
- this one is better than the first syntax. The -> operator signifies that 'r' is a POINTER to an object with a member function Do().
- this syntax is more advisable rather than the first one, because it is much easier to understand and remember.

Hope you found this helpful.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.