5

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];
        }
};
Rushil Paul
  • 2,010
  • 4
  • 26
  • 39

4 Answers4

6

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

sehe
  • 374,641
  • 47
  • 450
  • 633
  • can you explain what you've written as private code in class A ? – Rushil Paul Oct 14 '12 at 20:10
  • 1
    @Rushil Well, that is really off-topic: it's the quickest way to prevent `A` from being copied (which would lead to double deletion of `A::ar`). It's called [Rule Of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) or, in C++11 [Rule Of Zero](http://rmartinho.github.com/2012/08/15/rule-of-zero.html) instead :) – sehe Oct 14 '12 at 20:14
  • Okay. I know that's off topic but I wanted to know what that meant. :-) – Rushil Paul Oct 15 '12 at 18:55
5

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

}
kiv
  • 1,595
  • 1
  • 9
  • 11
1

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

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].

Ken
  • 2,105
  • 3
  • 19
  • 22