Search code examples
c++operatorsfieldmember

What is the difference between "::" "." and "->" in c++


I created a class called Kwadrat. The class has three int fields. My Development Environment suggests that I access the fields from Kwadrat created objects via the :: & -> operators. I tried both operators, and found that the -> operator is able to successfully access the data in the objects fields, although, the same cannot be said for the -> operator. I have also found that the . operator will access class members as well. I am confused, and don't understand why there are three members for accessing object members &/or methods. Can someone please explain to me what the difference is between the three operators?


          1. ->

          2. ::

          3. .




    #include <iostream>

    using namespace std;

    class Kwadrat{

    public: 
        int val1,
            val2,
            val3;

        Kwadrat(int val1, int val2, int val3)
        {
            this->val1 = val1; // Working
            this.val2 = val2;  // Doesn't Work!
            this::val3 = val3; // Doesn't Work!
        }
    };


    int main()
    {
        Kwadrat* kwadrat = new Kwadrat(1,2,3);

        cout<<kwadrat->val1<<endl;
        cout<<kwadrat->val2<<endl;
        cout<<kwadrat->val3<<endl;

        return 0;
    }



Solution

  • 1.-> for accessing object member variables and methods via pointer to object

    Foo *foo = new Foo();
    foo->member_var = 10;
    foo->member_func();
    

    2.. for accessing object member variables and methods via object instance

    Foo foo;
    foo.member_var = 10;
    foo.member_func();
    

    3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

    int some_val = Foo::static_var;
    Foo::static_method();
    int max_int = std::numeric_limits<int>::max();