0

I am learning C++, recently I encountered a problem and don't know why.

I want to hide the private member fields details from outside users, so I just declare a void* pointer as the only one private member field, and then declare the real member fields structure in class' .cpp source file. new this inner hidden structure in class constructor, and delete it in class destructor.

Below is my test codes:

ItemA.h

#pragma once

class ItemA
{
private:
    void* pFields;

public:
    ItemA();
    ~ItemA();
};

ItemA.cpp

#include "ItemA.h"
#include <string>

using namespace std;

typedef struct
{
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

ItemA::ItemA()
{
    this->pFields = new HFIELDS;
    PHFIELDS pHFIELDS = (PHFIELDS)this->pFields;
    pHFIELDS->intField = 100;
    pHFIELDS->strField = "100";
}

ItemA::~ItemA()
{
    PHFIELDS pHFIELDS = (PHFIELDS)this->pFields;
    delete pHFIELDS;
}

ItemB.h

#pragma once

#include "ItemA.h"

class ItemB
{
private:
    void* pFields;
    ItemB();

public:
    ItemB(ItemA &itemA);
    ~ItemB();
};

ItemB.cpp

#include "ItemB.h"
#include <string>

using namespace std;

typedef struct
{
    ItemA* pItemA;
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

ItemB::ItemB(ItemA &itemA)
{
    this->pFields = new HFIELDS;
    PHFIELDS pHFIELDS = (PHFIELDS)(this->pFields);
    pHFIELDS->pItemA = &itemA;
    pHFIELDS->intField = 200;
    pHFIELDS->strField = "200";
}


ItemB::~ItemB()
{
    PHFIELDS pHFIELDS = (PHFIELDS)this->pFields;
    delete pHFIELDS;
}

main.cpp

#include <tchar.h>
#include "ItemA.h"
#include "ItemB.h"

int _tmain(int argc, _TCHAR* argv[])
{
    ItemA* pItemA = new ItemA();
    ItemB* pItemB = new ItemB(*pItemA);
    delete pItemB;
    delete pItemA;

    return 0;
}

When program execution ran to ItemB's constructor this line it crashed:

pHFIELDS->strField = "200";

Could somebody tell me what's wrong with it? Thank you.

P.S. The development environment I use is MSVC2013.

J.K. Lau
  • 15
  • 3

1 Answers1

3

why do you have 2 declarations of HFIELDS and *PHFIELDS

1) In ItemA.cpp

typedef struct
{
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

2) In ItemB.cpp

typedef struct
{
    ItemA* pItemA;
    int    intField;
    string strField;
} HFIELDS, *PHFIELDS;

What happens is, ItemA.h is included in ItemB so the compiler sees 2 declarations.

Please change name and compile.

Hope this helps.