Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "::" and when to use "." [duplicate]

Tags:

c++

Apologies for a question that I assume is extremely basic.

I am having trouble finding out online the difference between the operator :: and . in C++

I have a few years experience with C# and Java, and am familiar with the concept of using . operator for member access.

Could anyone explain when these would be used and what the difference is?

Thanks for your time

like image 639
Jordan Avatar asked Jul 11 '12 22:07

Jordan


2 Answers

The difference is the first is the scope resolution operator and the second is a member access syntax.

So, :: (scope resolution) can be used to access something further in a namespace like a nested class, or to access a static function. The . period operator will simply access any visible member of the class instance you're using it on.

Some examples:

class A {
    public:

        class B { };

        static void foo() {}
        void bar() {}
};

//Create instance of nested class B.
A::B myB; 

//Call normal function on instance of A.
A a;
a.bar();

//Call the static function on the class (rather than on an instance of the class). 
A::foo(); 

Note that a static function or data member is one that belongs to the class itself, whether or not you have created any instances of that class. So, if I had a static variable in my class, and crated a thousand instances of that class, there's only 1 instance of that static variable still. There would be 1000 instances of any other member that wasn't static though, one per instance of the class.

One more interesting option for when you come to it :) You'll also see:

//Create a pointer to a dynamically allocated A.
A* a = new A();

//Invoke/call bar through the pointer.
a->bar();

//Free the memory!!! 
delete a;

Dynamic memory can be a little more confusing if you haven't learned it yet, so I won't go into details. Just wanted you to know that you can access members with { :: or . or -> } :)

like image 80
John Humphreys Avatar answered Oct 24 '22 21:10

John Humphreys


in C++ :: is the scope resolution operator. It is used to distinguish namespaces, and static methods, basically any case you don't have an object. Where . is used to access things inside an object.

C# uses the . operator for both of them.

namespace Foo
{
    public class Bar
    {          
        public void Method()
        {
        }

        public static void Instance()
        {
        }

    }
}

in C# you would write code like this:

var blah = new Foo.Bar();
blah.Method();

but the equivalent C++ code would look more like this:

Foo::Bar blah;
blah.Method();

But note that the static method would also be accessed using the scope resolution operator, because you're not referencing an object.

Foo::Bar::Instance();

Where again, the C# code would only use the dot operator

Foo.Bar.Instance();
like image 7
McKay Avatar answered Oct 24 '22 23:10

McKay