How to create an initialised object declared as a class member variable?

From: CFF (cffung_at_myrealbox.com)
Date: 08/18/04


Date: 18 Aug 2004 03:41:02 -0700

I am working on a VC6++ project that involve an object to be initialised
by a 'this' pointer pointing to another object. I encountered, however,
a syntax error. I wonder if someone can help. See the code below. What I
couldn't figure out is it is OK with

                       CMyClassA B2(this);

in fileB.cpp but a SYNTAX ERROR with

                       CMyClassA m_B2(this);
                       
in fileB.h. What should I do in order to create a initialised object of
CMyClassA if I really need a class member variable (m_B2) rather than a local (B2)?

Thanks for any help.

/////////////////////////// fileA.h ///////////////////////////
//
// forward declaration
class CMyClassB;

// CMyClassA declaration
class CMyClassA{
public:
        CMyClassB* m_ptA;

public:
        CMyClassA();
        CMyClassA(CMyClassB* ptB);
};

/////////////////////////// fileA.cpp /////////////////////////
//
#include "fileA.h"

// constructor 1
CMyClassA::CMyClassA(void){
        // ... whatever ...
}

// constructor 2
CMyClassA::CMyClassA(CMyClassB* ptB){
        m_ptA = ptB;
}

/////////////////////////// fileB.h ///////////////////////////
//
#include "fileA.h"

class CMyClassB{
public:
        CMyClassA m_B1; // no problem
        CMyClassA m_B2(this); // syntax error : 'this', WHY???

public:
        CMyClassB(void);
};

/////////////////////////// fileB.cpp //////////////////////////

#include "fileB.h"

CMyClassB::CMyClassB(void){
        CMyClassA B1; // no problem
        CMyClassA B2(this); // no problem
}

int main(void){
        // ... whatever ...
        return 1;
}



Relevant Pages