C++ Scope Rules

M

muler

Hi all,

Given (adapted from the C++ 98 standard document):

class A { };
class B : public A { };

namespace M {
namespace N {
class X : public B {
void f();
};
}
}

void M::N::X::f() {
i = 16;
}

Question: which scopes are searched for the declaration of i?

My answer:
1) outermost block scope of M::N::X::f, before the use of i
2) scope of class M::N::X
3) scope of M::N::X’s base class B
4) scope of M::N::X::B's base class A
5) scope of namespace M::N
6) scope of namespace M
7) global scope, before the definition of M::N::X::f

I'm not sure if i'm right about 4), can someone confirm?

Thanks,
 
V

Victor Bazarov

Given (adapted from the C++ 98 standard document):

class A { };
class B : public A { };

namespace M {
namespace N {
class X : public B {
void f();
};
}
}

void M::N::X::f() {
i = 16;
}

Question: which scopes are searched for the declaration of i?

My answer:
1) outermost block scope of M::N::X::f, before the use of i
2) scope of class M::N::X
3) scope of M::N::X’s base class B
4) scope of M::N::X::B's base class A
5) scope of namespace M::N
6) scope of namespace M
7) global scope, before the definition of M::N::X::f

I'm not sure if i'm right about 4), can someone confirm?

The base class of M::N::X is not M::N::X::B, it's ::B. Don't get
confused with the name M::N::X::B that designates the same thing as ::B
(imagine that inside M::N::X there is the declaration

typedef ::B B;

which allows you to use 'B' (unqualified) which the compiler will
interpret to mean '::B'.

So, if you rewrite your rules 3 and 4 to read

4) scope of B's base class A

the I would agree.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top