Difference between “::” “.” and “->” in c++ - c++

I have found the class Kwadrat. The author used three types of operator ::, . and ->. The arrow is the one that only works. What's the difference between those three?
#include <iostream>
using namespace std;
class Kwadrat{
public:
int val1, val2, val3;
Kwadrat(int val1, int val2, int val3)
{
this->val1 = val1;
//this.val2 = val2;
//this::val3 = val3;
}
};
int main()
{
Kwadrat* kwadrat = new Kwadrat(1,2,3);
cout<<kwadrat->val1<<endl;
cout<<kwadrat->val2<<endl;
cout<<kwadrat->val3<<endl;
return 0;
}

:: names a type within a namespace, a variable within a namespace, a static variable in a class, or a type in a class.
. names an instance variable or member function
a->b is syntactic sugar for (*a).b.

-> works on pointers, . on objects and :: on namespaces. Specifically:
Use -> or . when accessing a class/struct/union member, in the first case through a pointer, in the latter through a reference.
Use :: to reference the function inside a namespace or a class (namespaces), for instance, when defining methods declared with the class.

x->y is equivalent to (*x).y. That is, -> dereferences the variable before getting the field while the dot operator just gets the field.
x::y looks up y in namespace x.

The use cases are:
-> is used when you have a pointer
. is used when you have an object instance
:: is used when you have a static member or a namespace

The -> is the equivalent of saying (*Kwadrat_pointer).value. You use it when you have an object pointer calling object methods or retrieving object members.
The . operator is used to access the methods and members in the object that is calling it (that is, the object on the left side of the ".").
The :: operator is called the scope operator. It tells your program where to look, for example when defining a class method outside of the class declaration.

Related

What is the point of the scope resolution operators?

A question dawned on me lately: Why bother having the scope resolution operator (::) when the usage of the dot operator (.) doesn't clash with the former?
Like,
namespace my_module
{
const int insane_constant = 69;
int some_threshold = 100;
}
In order to access some_threshold, one would write my_module::some_threshold. But the thing is the left hand side of :: must be a namespace or a class, as far as I know, while that of the . can never be a namespace or a class. Moreover, the order of :: is higher than ., which is really pointless in my opinion. Why make 2 distinct operators, both of which cannot be overloaded, with use cases can be covered with just one? I'm having a hard time finding any satisfying answer, so any clue on this matter is much appriciated.
Consider the following code:
#include <iostream>
namespace my_module
{
const int insane_constant = 69;
}
class C{
public:
int insane_constant; // actually not constant, but for the example's sake
};
int main(){
C my_module;
my_module.insane_constant = my_module::insane_constant;
std::cout << my_module.insane_constant;
}
How would you distinguish my_module. from my_module:: here?
You can't replace one with the other.
Example:
namespace A
{
int x = 0;
struct X { int x = 1; } A;
void f()
{
std::cout << A.x
<< A::x
<< std::endl;
}
}
int main()
{
A::f();
}
prints "10".
Both operators have completely different purposes.
In particular, :: is for referring to a member of a scope while operator. is for referring to a member of an object.
That is, operator:: works on scope while operator. works on objects.
For instance, a classname::membername refers to the member of a class which has a class scope associated with it. On the other hand, object.membername refers to the member of the object object.
Note that not all scopes can be used with operator::. For example, we can refer to a namespace scope's member, class scopes' member(like a static member etc), enumeration' member etc using operator::.
The other answers showcase situations where :: and . do different things because they act on different entities (scopes vs objects). I'd like to add a bit of motivation behind this choice in the language by comparing it with the situation in C#. Disclaimer: I don't actually use C#, but these points seem obvious when looking into it.
In C#, the "namespace operator" is a dot ., just like the member access operator. However, you cannot have truly global variables: you need a class to put them in. In fact, you cannot even declare a class without a namespace, though this is unrelated to your question.
In C#, there is no possible ambiguity when using the dot between scope and object. Nested namespaces, classes within namespaces, class static variables, enumerators, and so on, are all accessed with a dot.
In C++, that's obviously not the case, and the language took the route of distinguishing between scopes and objects by having two distinct operators.
In plain C, there is no scope resolution, so there is no need for a :: operator. Other languages that make the distinction are Ruby and, apparently, PHP. Among languages that do not make the distinction, you can find for example Python, Go and Java. That last one does have a :: operator, but it's not for scope resolution, it's for forming method references.
In short, C++ has complex scope mechanisms because that's how the language was designed. As a result, it requires two different operators to distinguish scope access and object access.

What is the difference between "this" and "::"?

Inside setMyInt function I have used two statements to set myInt variable. Though both of them gives me the same result. Is there any conceptual difference in working of them?
#include <iostream>
using namespace std;
class Bar{
int myInt;
public:
const int getMyInt() const {
return myInt;
}
void setMyInt(int myInt) {
Bar::myInt = myInt;
this->myInt=myInt;
}
};
int main(){
Bar obj;
obj.setMyInt(5);
cout<<obj.getMyInt();
return 0;
}
You can't really compare them, and they are not interchangeable, but because in C++ you can leave certain things out in certain cases, here it looks like they are.
In fact, both lines are short for:
this->Bar::myInt = myInt;
This means, set the value of the object Bar::myInt (the member called myInt in the scope of the class Bar), which is encapsulated by the object pointed to by this, to the value of the (other) variable myInt.
You can leave out Bar:: because this is a Bar* so that's implicit; you can leave out this-> because you're in a member function so that's implicit too.
More generally, -> performs a pointer dereference and object access, whereas :: is the "scope resolution operator" which fully qualifies a name.
“->” is used as a pointer
“.” Is used for object members variables/ methods
“::” Is used for static variables/ methods or for objects from another scope.

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

This question already has answers here:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
(4 answers)
Closed 4 months ago.
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;
}
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();
In C++ you can access fields or methods, using different operators, depending on it's type:
ClassName::FieldName : class public static field and methods
ClassInstance.FieldName : accessing a public field (or method) through class reference
ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer
Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.
class AClass{
public:
static int static_field;
int instance_field;
static void static_method();
void method();
};
then you access this way:
AClass instance;
AClass *pointer = new AClass();
instance.instance_field; //access instance_field through a reference to AClass
instance.method();
pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();
AClass::static_field;
AClass::static_method();
Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow.
:: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static function.
. - This allows access to a member function on an already created object. For instance, Foo x; x.bar() calls the method bar() on instantiated object x which has type Foo. You can also use this to access public class variables.
-> - Essentially the same thing as . except this works on pointer types. In essence it dereferences the pointer, than calls .. Using this is equivalent to (*ptr).method()
You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *, and to access a field, you use ., so you can use:
cout << (*kwadrat).val1;
Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:
cout << kwadrat->val1;
These are defined to be identical. As you can see, the -> basically just combines a * and a . into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the . without dereferencing a pointer first:
Kwadrat kwadrat2(2,3,4);
cout << kwadrat2.val1;
The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:
struct something {
static int x; // this only declares `something::x`. Often found in a header
};
int something::x; // this defines `something::x`. Usually in .cpp/.cc/.C file.
In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:
something::x = 10;
std::cout << something::x;
Note, however, that it's also permitted to access a static member as if it was a member of a particular object:
something s;
s.x = 1;
At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.
The three operators have related but different meanings, despite the misleading note from the IDE.
The :: operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.
The . and -> operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).
The this object is always a pointer to the current instance, hence why the -> operator is the only one that works.
Examples:
// In a header file
namespace Namespace {
class Class {
private:
int x;
public:
Class() : x(4) {}
void incrementX();
};
}
// In an implementation file
namespace Namespace {
void Class::incrementX() { // Using scope resolution to get to the class member when we aren't using an instance
++(this->x); // this is a pointer, so using ->. Equivalent to ++((*this).x)
}
}
// In a separate file lies your main method
int main() {
Namespace::Class myInstance; // instantiates an instance. Note the scope resolution
Namespace::Class *myPointer = new Namespace::Class;
myInstance.incrementX(); // Calling a function on an object instance.
myPointer->incrementX(); // Calling a function on an object pointer.
(*myPointer).incrementX(); // Calling a function on an object pointer by dereferencing first
return 0;
}
-> is for pointers to a class instance
. is for class instances
:: is for classnames - for example when using a static member
The '::' is for static members.
Others have answered the different syntaxes, but please note, when you are doing your couts, you are only using ->:
int main()
{
Kwadrat* kwadrat = new Kwadrat(1,2,3);
cout<<kwadrat->val1<<endl;
cout<<kwadrat->val2<<endl;
cout<<kwadrat->val3<<endl;
return 0;
}

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

This question already has answers here:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
(4 answers)
Closed 8 years ago.
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
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 -> } :)
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();
:: is for namespaces and static member access. C# uses the dot-operator for namespaces instead.
. is for non-static member access.
Not an exhaustive delineation, but it's the relevant bits that may confuse you in light of C# and Java.
For further information, see
IBM - Scope Resolution Operator
IBM - Dot Operator
:: is the scope resolution operator, so when you are resolving a scope, such as a namespace or class, you use that. For member access, you have .
The scope operator :: may be hard to understand if you don't understand namespaces or classes. A namespace is like a container for the names of various things in your code. They're generally used to disambiguate names that are common across libraries. Say both namespaces std and example have the function foobar(). So the compiler knows which function you want to use, you prepend it as either std::foobar() or example::foobar().
The :: operator can also be used when telling the compiler you want to define a function declared in a class or structure. For instance:
class foobar()
{
public:
void hello();
int number; //assume there is a constructor that sets this to 5
}
void foobar::hello()
{
cout << "Hello, world!" << endl;
}
The . operator is used when you wish to use a member of a class or structure. For instance:
foobar foo;
foo.hello();
cout << foo.number << endl;
Assuming the class is completed by writing a constructor, the output of this would be expected to be:
Hello, world!
5
You use the . operator the same in java, when accessing members of a class once its created in the program.
the :: is used in number of cases:
When you define a method in the .h/.cpp of a certain class, write
class::methodName()
either for prototyping it, or implementing it.
Also, if you don't explicitly state what namespace you use, you'd have to to use it
std::cout << "This is the output";
instead of just using cout << "This is the output;
Maybe there are more, but i don't remember right now, my C++ is a bit rusty.
In C++, :: is for identifying scope. This can mean namespace scope or class scope.
Eg.
int x;
namespace N {
int x;
struct foo {
static double x;
double y;
};
struct bar: public foo {
double y;
};
}
int main()
{
int x; // we have a local, hiding the global name
x = ::x; // explicitly identify the x in global scope
x += N::x; // explicitly identify the x in namespace N
N::foo::x = x; // set the static member of foo to our local integer
N::foo f;
f.y = f.x; // the static member is implicitly scoped by the object
f.y += N::foo::x; // or explicitly scoped
N::bar b;
assert(b.x == N::foo::x); // this static member is inherited
b.y = b.x; // we get N::bar::y by default
b.N::foo::y = b.y; // explicitly request the hidden inherited one
}
// we need to define the storage for that static somewhere too ...
int N::foo::x (0.0);

not so obvious pointers

I have a class :
class X{
public :
void f ( int ) ;
int a ;
} ;
And the task is "Inside the code provide declarations for :
pointer to int variable of class X
pointer to function void(int) defined inside class X
pointer to double variable of class X"
Ok so pointer to int a will be just int *x = &a, right ? If there is no double in X can I already create pointer to double inside this class ? And the biggest problem is the second task. How one declares pointer to function ?
These are called pointers to members. They are not regular pointers, i.e. not addresses, but "sort-of" offsets into an instance of the class (it gets a bit tricky with virtual functions.) So:
int X::*ptr_to_int_member;
void (X::*ptr_to_member_func)( int );
double X::*ptr_to_double_member;
You need to declare them as pointer-to-members. Pointers to members are different than usual pointers in that they are the address of a member of a structure or class, not an absolute address like regular pointers.
For more information, read this.
A pointer to any type is declared with an '*' after the type name and the variable name:
Franks_Class * p_franks_class; // Declares a pointer to an instance of Franks_Class.
The more obscure declaration is for the function:
typedef void (*My_Int_Function_Ptr)(int parameter);
which declares a type (synonym), named My_Int_Function_Ptr, a pointer to a function taking an int parameter and returning void.
From this and a good C++ book, you should be able to answer the rest of your questions.