TITLE: using "this" too early? (Newsgroups: comp.std.c++, 22 May 98) GEORGESCU: Cristian Georgescu >I am trying to use "this" in the initialization list, for initializing >an attribute of the class. A simplified code sample (the real example >is more complicated) would be: > >class A >{ >public: > > A() : ptr(this) {} > > A*const ptr; >}; > >The compiler sends a warning like: > >warning C4355: 'this' : used in base member initializer list > >Running the program, shows that it works. However, I don't understand >the warning, and if it has to do with the standard usage of "this"? CLAMAGE: clamage@Eng (Steve Clamage) The potential problem with using "this" in an member initializer is that the recipient might expect that the object has been constructed, when in fact it hasn't been. Example: class Der; void f(Der*); class Base { public: Base(Der* d) { f(d); } }; class Der : public Base { public: Der() : Base(this) { ... } }; Function f gets passed a Der*, and would normally expect that the Der object has been constructed. In this case, the object isn't even a Der yet -- it's a Base! It's quite reasonable for the compiler to warn about passing "this" to a base class, since you've opened the door to a bug that might be hard to track down. Your simplified example is less problematic, but the compiler is warning you so that you realize you must be careful about using "ptr" in the constructor for A.