Trying to get rid of some errors in someone else's old C++ code.
Consider:
class Base
{
public:
int i_;
Base(int i) : i_(i) {};
};
class Derived
{
public:
int j_;
Derived(int i, int j) : Base(i), j_(j) {} ;
};
Visual C++ objects:
warning C4355: 'this' : used in base member initializer list
and the help says:
I think this will wind up being OK as long as none of Derived's members attempt to use any of Base's members, but I'd like to get rid of the compiler warning, as it's in a header file that's used in 11 source files, and generates a couple of dozen warnings. IIRC, class initializers like this happen before the constructor. That may or may not matter. Wouldn'tThe this pointer is valid only within nonstatic member functions. It cannot be used in the initializer list for a base class.
The base-class constructors and class member constructors are called before this constructor. In effect, you've passed a pointer to an unconstructed object to another constructor. If those other constructors access any members or call member functions on this, the result will be undefined. You should not use the this pointer until all construction has completed.
The following sample generates C4355:
Copy Code
// C4355.cpp
// compile with: /W1 /c
#include <tchar.h>
class CDerived;
class CBase {
public:
CBase(CDerived *derived): m_pDerived(derived) {};
~CBase();
virtual void function() = 0;
CDerived * m_pDerived;
};
class CDerived : public CBase {
public:
CDerived() : CBase(this) {}; // C4355 "this" used in derived c'tor
virtual void function() {};
};
CBase::~CBase() {
m_pDerived -> function();
}
int main() {
CDerived myDerived;
}
Derived(int i, int j)
{
i_ = i;
j_ = j;
}
be correct as long as there are no oddball side effects (which I believe is the case?)


Reply With Quote

