c++pointersscope-resolution-operator

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


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

MyClass->m_Integer // 1
MyClass::m_Integer // 2
MyClass.m_Integer  // 3

Solution

  • 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();