Search code examples
c++objectreferenceshareinitializer-list

C++: Sharing an object between two other objects


There are 1 main class and 3 classes: Main, MLME, MAC and Network.

I would want an MLME object to be created within the MAC object upon calling the constructor of the MAC. Then share the same object to the Network object when calling the Network constructor.

This without making the MLME object global or allocating memory with malloc() or new.

I believe this should be done with references which I don't understand fully. Also there might have to be some initializer-list in Network.cpp? I am more experienced with C than C++ and have tried a lot in order to understand all of this.

This is some of my thoughts of the structure, header and cpp files:

Main.cpp

#include "MAC.h"
#include "Network.h"

int main() {

    MAC mac();
    Network network(mac);

    return 0;
}

Here is the MLME part to be shared:

MLME.h

#ifndef MLME_H_INCLUDED
#define MLME_H_INCLUDED

class MLME {
public:
    MLME();
};

#endif

MLME.cpp

#include "MLME.h"

MLME::MLME() {}

The MAC class:

MAC.h

#ifndef MAC_H_INCLUDED
#define MAC_H_INCLUDED

#include "MLME.h"

class MAC {
private:
    MLME mlme; // NULLED ?
public:
    MAC();
MLME getMLME();
};

#endif

MAC.cpp

#include "MAC.h"

MAC::MAC() {
    mlme = MLME:MLME();
}

MLME MAC::getMLME() {
    return mlme;
}

The Network class:

Network.h

#ifndef NETWORK_H_INCLUDED
#define NETWORK_H_INCLUDED

#include "MLME.h"

class Network {
private:
    MLME& mlme;
public:
    Network(MAC mac);
};

#endif

Network.cpp

#include "Network.h"

class MAC;

Network::Network(MAC mac) {
    mlme = mac.getMLME();
}

Solution

  • You're close, but:

    • The Network::Network constructor should take MAC by reference, like so: Network::Network(MAC& mac). Currently you take a copy, which means taking a copy of MLME as well.
    • In addition, the Network::Network constructor should use an initializer list to initialize mlme. So the full form would be:
    Network::Network(MAC& mac) : mlme(mac.getMLME()) {}
    
    • MAC::getMLME() should return a reference to MLME: MLME& MAC::getMLME(). Otherwise you return a copy.
    • The explicit construction of MLME in the MAC constructor is not needed: it is already default-constructed.
    • You may want to prevent copying of MLME instances by saying MLME(const MLME&) = delete. If it is really a shared resource, you want any changes to go back to the shared instance. Making it impossible to copy MLME instances will prevent you from accidentally making or modifying a copy.
    • In your main function: MAC mac() does not do what you think it does. Remove the () or you get a "most vexing parse" error.