Hello,

I am new to C++ and have been writing a server program to help me learn. I am currently stuck on how to get a couple of classes passed by reference. I have been searching on forums for hours now and I just can't figure this out. I would be extremely grateful if someone can help me with this:

//header
class Player
{
public:
    void SetParents(Server *ParentServer, Client *ParentClient);

private:
    Client *__parent_client;
    Server *__parent_server;
};

//implimentation

void Player::SetParents(Server *ParentServer, Client *ParentClient)
{
    __parent_server = ParentServer;
    __parent_client = ParentClient;
}

The SetParents method is then called by:

            if (FreeIdx != -1) // Free index found!
            {
                // note: __clients is of type "vector<Client>"
                __clients->at(FreeIdx) = Client(NewClient.Descriptor, FreeIdx, NewClientIP, &*this); // Init the client

                __clients->at(FreeIdx).GetPlayer()->SetParents(&*this, &__clients->at(FreeIdx)); // Set pointers to server and client classes

                cout << "New client accepted from " << NewClientIP << ", ID: " << FreeIdx << endl;
            }

Now the obvious problem is I'm not passing by reference to SetParents(), but I can't for the life of me figure out how to do so. I have read many different articles but none explain how to resolve the situation I am in with this. Ideally I really do need these pointers passed as the class will rely on them.

Just for clarity, the two classes (or objects) being passed are Server and Client. The Server class is where SetParents is being called from and the Client class is the index within the __clients vector located at "FreeIdx".

Hope that all makes sense.

Thanks for reading.

SetParents() does not need a reference to a pointer -- just the pointer

_clients->at(FreeIdx).GetPlayer()->SetParents(this, __clients->at(FreeIdx));

When passing a poitner by reference the & operator is not used in the actional function call, only in the function prototype and function header. The & in the actual function call makes it a pointer to a pointer, not a reference to a pointer.

Thanks Ancient, it seems quite easy now. I wish some of the so-called tutorials would have stated what you just told me rather than just generic examples! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.