What's the difference between these two statements?
ob.A::ar[0] = 200;
ob.ar[0] = 200;
where ob
is an object of class A
class A
{
public:
int *ar;
A()
{
ar = new int[100];
}
};
What's the difference between these two statements?
ob.A::ar[0] = 200;
ob.ar[0] = 200;
where ob
is an object of class A
class A
{
public:
int *ar;
A()
{
ar = new int[100];
}
};
There is no difference. The explicit namespace qualification of ar
is redundant in this case.
It might not be redundant in cases where (multiple, nonvirtual) inheritance redefines the name ar
. Sample (contrived):
#include <string>
class A
{
public:
int *ar;
A() { ar = new int[100]; }
// unrelated, but prevent leaks: (Rule Of Three)
~A() { delete[] ar; }
private:
A(A const&);
A& operator=(A const&);
};
class B : public A
{
public:
std::string ar[12];
};
int main()
{
B ob;
ob.A::ar[0] = 200;
ob.ar[0] = "hello world";
}
See it on http://liveworkspace.org/code/d25889333ec378e1382cb5af5ad7c203
In this case there is no difference.
This notation:
obj.Class::member
is only to solve the ambiguities coming from inheritance:
class A {
public:
int a;
}
class B {
public:
int a;
}
class C : public A, B {
void func() {
// this objects holds 2 instance variables of name "a" inherited from A and B
this->A::a = 1;
this->B::a = 2;
}
}
In this case there is no difference. However imagine that ob is of class C that inherits both from class A and class B and both A and B have a field ar. Then there will be no other way to access ar but to explicitly specify which of the inherited data members you are refering to.
You are supposed to read this
ob.A::ar[0] = 200;
ob.ar[0] = 200;
like this
A::ar[0]
it's the same thing for ar[0]
, so the 2 rows are basically the same thing and the operator ::
is used to indicate the so called resolution of the namespace, or just the namespace.
since ob
is an object of type A, the namespace resolution is implicit and you do not need A::
before accessing ar[0]
.