Mark A. Donohoe
Mark A. Donohoe

Reputation: 30408

In C++, can you have a class member be a passed-in reference?

I have a 'StripManager' class that is responsible for updating the data of an already-existing 'Strip' class. As such, the manager needs a reference to the strip. Now I know I can pass in a pointer to the 'Strip' class to the constructor of the 'StripManager' class, but I'm wondering if there's any way to do that using references instead of pointers. I just have always preferred dealing with references since you use them like the actual class instance rather than having to deal with pointer notation, etc.

So can this be done?

Here's some pseudo-code...

class StripManager
{
  public: 
    Strip &managedStrip;
    StripManager(Strip &stripToManage);
}

StripManager::StripManager(Strip &stripToManage)
{
    managedStrip = stripToManage;
}

Upvotes: 0

Views: 69

Answers (2)

T.C.
T.C.

Reputation: 137325

You can initialize a reference, but not assign to it, so you need to use the member initializer list for this. It's good habit to use it instead of assignment in constructors anyway as it can be more efficient.

StripManager::StripManager(Strip &stripToManage) : managedStrip (stripToManage)
{
}

Note that having a reference member makes StripManager non-assignable (StripManager a(strip1), b(strip2); a = b; won't compile unless you write a custom assignment operator; even then, since you can't assign references, it's unclear what the semantics should be), which may or may not be a problem depending on your particular situation.

Upvotes: 1

Eric Z
Eric Z

Reputation: 14505

A reference can only be initialized but not assigned. So you cannot reassign the reference itself. You can do it in member initialization list to initialize the reference member.

class StripManager
{
  public: 
    Strip &managedStrip;
    StripManager(Strip &stripToManage);
};

StripManager::StripManager(Strip &stripToManage): managedStrip(stripToManage)
{}

Upvotes: 4

Related Questions