Passing and storing a const reference via a constructor?

29,209
class    ClassB
{
    private:
        const int&    internalX;
    public:
        ClassB(const int& tempX);
}

ClassB::ClassB(const int& tempX):
     internalX(tempX)
{
}

As you said, a reference has to be initialized immediately. Thus, if you want your reference to be a class member, you have to use your constructor's initialization list to set it.

(This short explanation might also make things clearer for you, as it is specifically centered on the situation you've just met)

Good luck

Share:
29,209
MrKatSwordfish
Author by

MrKatSwordfish

Updated on January 05, 2020

Comments

  • MrKatSwordfish
    MrKatSwordfish over 4 years

    This is probably a simple question, but I'm stuck on it. I'm trying to pass an object down from ObjectA to ObjectB (which is a member of ObjectA) via it's constructor. However, instead of passing by value, I want to pass only a const reference and store that reference indefinitely. The problem is that I'm not sure how to do it.

    I can get this working with pointers like this:

    class ClassB
    {
    private:
        int *ptrInternalX;
    public:
        ClassB( int *tempX );
    }
    
    ClassB::ClassB( int *tempX )
    {
        ptrInternalX = tempX
    }
    

    This way, an object is created and passed a pointer to an int, and that pointer is stored inside the class for later use.

    However, pointers make me worry about memory leaks and other issues when using larger objects, so I'd like to try to do something like this using 'constant references' (const &). However, this doesn't seem to work...

    class ClassB
    {
    private:
        int &internalX;
    public:
        ClassB( const int &tempX );
    }
    
    ClassB::ClassB( const int &tempX )
    {
        internalX = tempX
    }
    

    I know that references are essentially an 'alias' for an existing variable (a different name that refers to the same memory address), and they need to be initialized immediately using an existing variable. So this creates an error in my program!

    Is this even possible? Or is there a better/more clear way of doing something like this? The reasons I want to use constant references are the speed of passing just a reference instead of a large object while keeping the data safe from accidental changes and memory leaks... I'm sure that there is a simple and straight-forward way to do this but I'm not very familiar with const reference passing.