The arrow operator (->) in C++

Written by Hamza on. Posted in C++

Let us now look at another interesting feature that pops up whenever dealing with classes in C++: the arrow operator. The arrow operator is used to access member functions within a class through a pointer. It is a very useful feature and makes object oriented programming in C++ a lot easier.

What the arrow operator does is deference a pointer(pointing towards an object) and then use the ‘ . ‘ operator on the leftover expression. To further clarify, basically:

</p>
<p>obj->function();</p>
<p>.</p>
<p>

is the same as:

</p>
<p>(*obj).function();</p>
<p>.</p>
<p>

This is to avoid confusion with this:

</p>
<p>*(obj.function());</p>
<p>.</p>
<p>

which of course could be disastrous and could cause program crashes.

To clarify even further, look at the following code:

</p>
<p>class fraction</p>
<p>{</p>
<p>private:</p>
<p>.  int num;</p>
<p>.  int den;</p>
<p>public:</p>
<p>int get_num() <a style="text-decoration: none;font : inherit;box-shadow: none ; color : inherit;cursor: default" href="http://badocams.com/group-sex">chat</a></p>
<p>{</p>
<p>. return num;<br />
}</p>
<p>};</p>
<p>&nbsp;</p>
<p>int main()</p>
<p>{</p>
<p>.  fraction * obj = new fraction ;</p>
<p>.  obj->get_num () ;</p>
<p>}</p>
<p>

 

This is a simple example of arrow operator that we have seen before when explaining getters. Here, we have returned the private data member ‘num’ in a  getter function and called it using a pointer, obj, pointing towards an object using the arrow operator.

The object oriented programming series is gonna get a bit more complex from now on, as we’ve covered most of the basics. Stay tuned for the next article!

Tags: , , ,