Anon_unique
Anon_unique

Reputation: 45

C++ shadowing variable name

If a C++ class member function accesses a variable name that is overloaded with definitions both as a member variable of the class and a variable in the global scope of the member function’s definition, which one will the member function actually access? The scenario is like this:

SomeClass.h:

class   SomeClass
{
    int Num;
    void    OperateOnNum();
};

SomeClass.cpp:

#include "SomeClass.h"
int Num;
void    SomeClass::OperateOnNum()
{
    Num = 0;
}

Which Num will OperateOnNum operate on? Neither Microsoft Visual Studio 2013 nor GCC (Version: gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2) issues a warning.

Upvotes: 1

Views: 2187

Answers (3)

Lorah Attkins
Lorah Attkins

Reputation: 5856

You can always use this and global scope resolution to dissambiguate between the two

this->Num; // refers to the member Num
::Num;     // refers to the global Num

A good design though, shouldn't have to resort to such methods. You can mark member names and globals (which are a "don't" on their own) accordingly :

_name;  // member name prefixed with _
m_name; // member name prefixed with m_
global_name; // global name - prefixed with global_

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70989

In this case the class member parameter shadows the global variable. Thus you see it in the scope of the method.

Upvotes: 0

jmajnert
jmajnert

Reputation: 418

The class variable shadows the global variable. If you want to access the global variable do it like this:

void SomeClass::OperateOnNum()
{
    ::Num = 0;
}

There's no warnings, because that's just how the language works.

Upvotes: 4

Related Questions