Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ".", "::" and, "->"

Tags:

c++

In c++ is there any difference between these 3 blocks of code:

MyClass->m_Integer // 1
MyClass::m_Integer // 2
MyClass.m_Integer  // 3
like image 863
Sheldon Allen Avatar asked Nov 29 '22 18:11

Sheldon Allen


1 Answers

The -> and . operators are way to access members of an instance of a class, and :: allows you to access static members of a class.

The difference between -> and . is that the arrow is for access through pointers to instances, where the dot is for access to values (non-pointers).

For example, let's say you have a class MyClass defined as:

class MyClass
{
public:
    static int someValue();
    int someOtherValue();
};

You would use those operators in the following situations:

MyClass *ptr = new MyClass;
MyClass value;

int arrowValue = ptr->someOtherValue();
int dotValue = value.someOtherValue();
int doubleColonValue = MyClass::someValue();

In Java, this would look like:

MyClass ref = new MyClass;

int dotValue = ref.someOtherValue();
int doubleColonValue = MyClass.someValue();
like image 159
Daniel Gallagher Avatar answered Dec 18 '22 10:12

Daniel Gallagher