f



class ctor argument variable name and class member variable name

I've read some code like below:
       class Foo
	{
		int foo;
	public :
		Foo(int foo)
			:foo(foo)
		{}
	};
I try it in VC2008, and it is fine.

My question is :in the ctor, the name "foo" here does not cause any
ambiguity, why that? Is this a standard way or just a workaround ?

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
zade
11/5/2008 8:06:27 AM
comp.lang.c++.moderated 10738 articles. 1 followers. allnor (8506) is leader. Post Follow

2 Replies
345 Views

Similar Articles

[PageSpeed] 28

On Nov 5, 8:06 am, zade <zhaohongc...@gmail.com> wrote:
> I've read some code like below:
>        class Foo
>         {
>                 int foo;
>         public :
>                 Foo(int foo)
>                         :foo(foo)
>                 {}
>         };
> I try it in VC2008, and it is fine.

The scope of these variables are different.  So they are fine.  The
local variable hides the member variable.  Consider the following
example where the local variable hides the global variable.

$ cat scope.cc
#include <iostream>
int foo(28);
int main(){
   int foo(82);
   std::cout << foo << std::endl;
}

$ g++ -Wall -Wall -pedantic scope.cc
$ ./a.exe
82
$

Rgds,
anna

--
Sicko (The Documentary)
http://missingrainbow.blogspot.com/2008/01/sicko.html


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
annamalai
11/5/2008 4:13:30 PM
On Nov 5, 3:06 pm, zade <zhaohongc...@gmail.com> wrote:
> I've read some code like below:
>        class Foo
>         {
>                 int foo;
>         public :
>                 Foo(int foo)
>                         :foo(foo)
>                 {}
>         };
> I try it in VC2008, and it is fine.
>
> My question is :in the ctor, the name "foo" here does not cause any
> ambiguity, why that? Is this a standard way or just a workaround ?

It's standard-compliant. Whether it's a good idea is up to your taste.
C++03 12.6.2p1 gives this production for initializer lists:

mem-initializer-list:
    mem-initializer
    mem-initializer , mem-initializer-list

mem-initializer:
    mem-initializer-id ( expression-list[opt] )

12.6.2p2 then says:

  Names in a mem-initializer-id are looked up in the scope of the
constructor's class and,
  if not found in that scope, are looked up in the scope containing
the constructor's
  definition.

Note in particular that names are not looked up within the scope of
the constructor itself, so the parameters are not found.

The expression list itself follows normal name lookup rules, which
means that the parameters hide the member variables.

Sebastian


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
wasti
11/5/2008 4:14:21 PM
Reply: