An example of C++ dot vs. arrow usage

vs.

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
{
public:
	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;
	x.Create();
 
	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;
	y->Create();
}

1 thought on “An example of C++ dot vs. arrow usage”

Leave a Comment