An example of C++ dot vs. arrow usage


Overall, dot(.) is for object itself, arrow(->) is for pointer.

A good example worth a thousand words. The following example should be a good one.

#include <iostream>
using namespace std;
class Car
	int number;
	void Create() 
		cout << "Car created, number is:  " << number << "\n" ;
int main() {
	Car x;
	// declares x to be a Car object value,
	// initialized using the default constructor
	// this very different with Java syntax Car x = new Car();
	x.number = 123;
	Car *y; // declare y as a pointer which points to a Car object
	y = &x; // assign x's address to the pointer y
	(*y).Create(); // *y is object
	y->Create(); // same as previous line, y points to x object. It stores a reference(memory address) to x object.
	y->number = 456; // this is equal to (*y).number = 456;
Category >> C/C++ >> Versus  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. yahia farghaly on 2014-8-3

    great explanation !

Leave a comment