0

Consider the following class definitions:

#include <string>

class CParty
{
public:
    CParty();
    virtual ~CParty();
    int m_nId;
};

class CPartyEx : public CParty
{
public:
    CPartyEx();
    ~CPartyEx();
    std::string m_sName;
};

class CTransaction
{
public:
    CTransaction();
    virtual ~CTransaction();
    int m_nClassNo;
};

class CTransactionEx : public CTransaction
{
public:
    CTransactionEx();
    ~CTransactionEx();
    std::string m_sDesc;
};

class CObject
{
public:
    CObject();
    ~CObject();
    CParty* m_pParent;
    CTransaction* m_pTransaction;
};

In an appropriate implementation, I would like to create the following types of CObject storage objects:

// OK: Basic party with basic transaction
CObject iObject1;
iObject1.m_pParent = new CParty();
iObject1.m_pTransaction = new CTransaction();

// OK: Extended party with extended transaction
CObject iObject2;
iObject2.m_pParent = new CPartyEx();
iObject2.m_pTransaction = new CTransactionEx();

However, the current CObject definition does not prevent mixing CParty and CTransaction types which are incompatible with one another:

// Not intended: Basic party with extended transaction
CObject iObject3;
iObject3.m_pParent = new CParty();
iObject3.m_pTransaction = new CTransactionEx();

// Not intended: Extended party with basic transaction
CObject iObject4;
iObject4.m_pParent = new CPartyEx();
iObject4.m_pTransaction = new CTransaction();

Is it somehow possible to place a restriction on how the two objects can be linked together inside a CObject instance?

Aurora
  • 1,334
  • 8
  • 21
  • 1
    Would encapsulating the decision in a constructor work for you? – TartanLlama May 08 '15 at 07:53
  • Could you please explain what you mean by this? – Aurora May 08 '15 at 07:56
  • 1
    Do the assignments take place only at the construction of a 'CObject' ? Otherwise you can insert a memberfuction to create the depending objects. And by the way, do you thougt about using 'std::unique_ptr' instead of raw pointers ? – Tunichtgut May 08 '15 at 08:34

1 Answers1

1

You could encapsulate the decision in the CObject constructor:

class CObject
{
public:
    CObject(bool extended = false);
};

CObject::CObject (bool extended)
{
    if (extended)
    {
        m_pParent = new CPartyEx();
        m_pTransaction = new CTransactionEx();
    }
    else
    {
        m_pParent = new CParty();
        m_pTransaction = new CTransaction();
    }
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193