When to use "::" and when to use "." [duplicate] - c++

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

Related

Can you use a class without objects?

EDIT: No... I dont wanna use :: I want to be able to use . when using static method
EDIT 2: Not a namespace. A class/struct is what I'm trying to use!
I bet this has been asked and answered before but I cant find an answer
Suppose I have a class called "A"
struct A {
void log(const char* x) {
std::cout << x << std::endl;
}
}
If i want to use this class i need to do something like A B;
Then i can do something like B.log("Hello World!");
But is there any possible way I dont have to make an object to use a class? I just want to be able to do A.log("Hello World!");
Is that possible?
Can you use a class without objects?
Yes, you can. For example, you can access static members of a class.
I want to be able to use . when using static method
You cannot do what you want. The member access operator . can only be used on values of the class type and for that you need an object. The operator to access static member function of a class without an object is the scope resolution operator ::.
You also cannot call a non-static member function - such as A::Log of your example - without an instance regardless of syntax.
An alternative to using a class could be to use a namespace instead:
namespace A {
void log(const char* x) {
std::cout << x << std::endl;
}
}
That way, your class doesn't need to exist, it can just be a free-function inside it's own namespace. You even call it the same way:
A::log("foo");
You need to change your code as follows,
class A {
static void log(const char* x) {
std::cout << x << std::endl;
}
}
//Call it as follows,
A::log("hello");
Observe the word, static. static methods are class level methods and should be called via class. You will not be able to call it with objects of the class A.
You can use struct instead of class if you like :-)
But is there any possible way I dont have to make an object to use a class? I just want to be able to do A.log("Hello World!");
To use that syntax, you need an object.
With a small change, you can have your expected syntax:
/*inline*/ struct {
void log(const char* x) {
std::cout << x << std::endl;
}
} A;
Demo
Anonymous class, with variable A of that type.
If put in header included at several place, adding inline or static would avoid ODR-violation.
Using regular way (static method and A::log) is less surprising.

Is this language issue? Access private nested class in c++ using decltype. [duplicate]

This question already has answers here:
Why can I use auto on a private type?
(5 answers)
Closed 7 years ago.
I have been playing around with inner classes in C++, and I'm bit confused right now.
My Code:
#include <iostream>
class outer{
private:
class inner{
private:
int something;
public:
void print(){
std::cout<< "i am inner"<<std::endl;
}
};
public:
inner returnInner(){
inner i;
return i;
}
};
int main(){
outer o;
//outer::inner i = o.returnInner(); (1)
//auto i = o.returnInner(); (2)
//i.print();
o.returnInner().print(); //(3)
return 0;
}
This is compiled on Linux with clang++-3.5 and -std=c++14.
In (1) I'm getting a compiler error as expected because inner is a private inner class of outer.
However, in (2) when the auto keyword is used, compilation is successful and the program runs.
Everything works for (3), too.
My question:
Why is this so? Can I prevent returning an instance of private inner class from outer methods while retaining the ability to move and/or copy them within the outer class?
Shouldn't the compiler elicit an error in (2) and (3) like it does in (1)?
why is it so
Shouldn't compiler return error in (2) and (3) as in (1)?
It is an interesting question.. and answer to this is even more interesting.
In the code you posted, inneris a name of a type. It is the name which is declared to be private, not the type itself1 — accessibility of type doesn't make sense in the context of C++; accessibilty applies to name only — be it name of type, name of function, name of data . So when you hear something like "the type X is a public class", it almost always means "the name X is declared to be public, and it refers to a type and the type is omnipresent, it exists everywhere".
Coming back to why using auto doesn't give error, well because when you use auto, you're accessing the type without using its name, which is why it doesn't give error.
how can i prevent return of an instance of private inner class from outer methods,
There is no way.
1. struct { int data; } is a type, without a name to refer to, though note that is not a valid declaration, because it lacks name. Either you've to declare an object of unnamed type as in struct { int data; } obj; Or give it a name as struct data_type { int data; };
I'm not sure that it's what you want but you can delete the copy constructor like that:
inner(inner const&) = delete;

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;
}

Why does C++ need the scope resolution operator?

(I know what the scope resolution operator does, and how and when to use it.)
Why does C++ have the :: operator, instead of using the . operator for this purpose? Java doesn't have a separate operator, and works fine. Is there some difference between C++ and Java that means C++ requires a separate operator in order to be parsable?
My only guess is that :: is needed for precedence reasons, but I can't think why it needs to have higher precedence than, say, .. The only situation I can think it would is so that something like
a.b::c;
would be parsed as
a.(b::c);
, but I can't think of any situation in which syntax like this would be legal anyway.
Maybe it's just a case of "they do different things, so they might as well look different". But that doesn't explain why :: has higher precedence than ..
Because someone in the C++ standards committee thought that it was a good idea to allow this code to work:
struct foo
{
int blah;
};
struct thingy
{
int data;
};
struct bar : public foo
{
thingy foo;
};
int main()
{
bar test;
test.foo.data = 5;
test.foo::blah = 10;
return 0;
}
Basically, it allows a member variable and a derived class type to have the same name. I have no idea what someone was smoking when they thought that this was important. But there it is.
When the compiler sees ., it knows that the thing to the left must be an object. When it sees ::, it must be a typename or namespace (or nothing, indicating the global namespace). That's how it resolves this ambiguity.
Why C++ doesn't use . where it uses ::, is because this is how the language is defined. One plausible reason could be, to refer to the global namespace using the syntax ::a as shown below:
int a = 10;
namespace M
{
int a = 20;
namespace N
{
int a = 30;
void f()
{
int x = a; //a refers to the name inside N, same as M::N::a
int y = M::a; //M::a refers to the name inside M
int z = ::a; //::a refers to the name in the global namespace
std::cout<< x <<","<< y <<","<< z <<std::endl; //30,20,10
}
}
}
Online Demo
I don't know how Java solves this. I don't even know if in Java there is global namespace. In C#, you refer to global name using the syntax global::a, which means even C# has :: operator.
but I can't think of any situation in which syntax like this would be legal anyway.
Who said syntax like a.b::c is not legal?
Consider these classes:
struct A
{
void f() { std::cout << "A::f()" << std::endl; }
};
struct B : A
{
void f(int) { std::cout << "B::f(int)" << std::endl; }
};
Now see this (ideone):
B b;
b.f(10); //ok
b.f(); //error - as the function is hidden
b.f() cannot be called like that, as the function is hidden, and the GCC gives this error message:
error: no matching function for call to ‘B::f()’
In order to call b.f() (or rather A::f()), you need scope resolution operator:
b.A::f(); //ok - explicitly selecting the hidden function using scope resolution
Demo at ideone
Why does C++ have the :: operator, instead of using the . operator for this purpose?
The reason is given by Stroustrup himself:
In C with Classes, a dot was used to express membership of a class as well as expressing selection of a member of a particular object.
This had been the cause of some minor confusion and could also be used to construct ambiguous examples. To alleviate this, :: was introduced to mean membership of class and . was retained exclusively for membership of object
(Bjarne Stroustrup A History of C++: 1979−1991 page 21 - § 3.3.1)
Moreover it's true that
they do different things, so they might as well look different
indeed
In N::m neither N nor m are expressions with values; N and m are names known to the compiler and :: performs a (compile time) scope resolution rather than an expression evaluation. One could imagine allowing overloading of x::y where x is an object rather than a namespace or a class, but that would - contrary to first appearances - involve introducing new syntax (to allow expr::expr). It is not obvious what benefits such a complication would bring.
Operator . (dot) could in principle be overloaded using the same technique as used for ->.
(Bjarne Stroustrup's C++ Style and Technique FAQ)
Unlike Java, C++ has multiple inheritance. Here is one example where scope resolution of the kind you're talking about becomes important:
#include <iostream>
using namespace std;
struct a
{
int x;
};
struct b
{
int x;
};
struct c : public a, public b
{
::a a;
::b b;
};
int main() {
c v;
v.a::x = 5;
v.a.x = 55;
v.b::x = 6;
v.b.x = 66;
cout << v.a::x << " " << v.b::x << endl;
cout << v.a.x << " " << v.b.x << endl;
return 0;
}
Just to answer the final bit of the question about operator precedence:
class A {
public:
char A;
};
class B : public A {
public:
double A;
};
int main(int c, char** v)
{
B myB;
myB.A = 7.89;
myB.A::A = 'a';
// On the line above a hypothetical myB.A.A
// syntax would parse as (myB.A).A and since
// (myB.A) is of type double you get (double).A in the
// next step. Of course the '.' operator has no
// meaning for doubles so it causes a syntax error.
// For this reason a different operator that binds
// more strongly than '.' is needed.
return 0;
}
I always assumed C++ dot/:: usage was a style choice, to make code easier to read. As the OP writes "they do different things, so should look different."
Coming from C++, long ago, to C#, I found using only dots confusing. I was used to seeing A::doStuff(); B.doStuff();, and knowing the first is a regular function, in a namespace, and the second is a member function on instance B.
C++ is maybe my fifth language, after Basic, assembly, Pascal and Fortran, so I don't think it's first language syndrome, and I'm more a C# programmer now. But, IMHO, if you've used both, C++-style double-colon for namespaces reads better. I feel like Java/C# chose dots for both to (successfully) ease the front of the learning curve.
Scope resolution operator(::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name.