Topic: typedef and data member in a class
Author: "subramanian100in@yahoo.com, India" <subramanian100in@yahoo.com>
Date: Mon, 26 Nov 2007 11:40:50 CST Raw View
consider the following program:
class Test
{
public:
Test(Test_int arg = 0) : val(arg) { }
typedef int Test_int;
private:
Test_int val;
};
int main()
{
return 0;
}
This results in compilation error with g++ because
the typedef statement comes after the ctor. The
definition of the data member 'val' also comes after
the ctor. However the compiler is able to see the
data member 'val' but not the typedef 'Test_int'
which is used in the ctor. Why is it so ? What is
the difference between the two scenarios ?
Kindly explain
Thanks
V.Subramanian
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Author: francis.glassborow@btinternet.com (Francis Glassborow)
Date: Mon, 26 Nov 2007 19:27:14 GMT Raw View
subramanian100in@yahoo.com, India wrote:
> consider the following program:
>
> class Test
> {
> public:
> Test(Test_int arg = 0) : val(arg) { }
> typedef int Test_int;
>
> private:
> Test_int val;
> };
>
> int main()
> {
> return 0;
> }
>
> This results in compilation error with g++ because
> the typedef statement comes after the ctor. The
> definition of the data member 'val' also comes after
> the ctor. However the compiler is able to see the
> data member 'val' but not the typedef 'Test_int'
> which is used in the ctor. Why is it so ? What is
> the difference between the two scenarios ?
Because for the purpose of a decalration the compiler only needs to know
the types of the argument. As the ctor comes before the typedef the
compiler is required not to know about it for the purpose of the
declaration (The reason for that being required is that the typedef
might hide an outer typename spelt the same way. In such a case it will
not spot the error till the end of the class definition.
Now definitions (i.e the bodies of the functions and ctor init list) of
member functions are compiled as if they were delayed until the end of
the class definition. So the compiler will see the declaration of val
before it considers the definition of the ctor.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]