简体   繁体   中英

Reference to object must be initialized in constructor base/member initializer list

Forgive me, I'm a bit rusty with my C++.

I'm trying to create a Singleton via an interface (such that, the system can easily be expanded upon later as needed).

I've got the following interface:

#ifndef IBUILD_CONFIGURATION_H
#define IBUILD_CONFIGURATION_H

*IBuildConfiguration.h*
class IBuildConfiguration
{
    public:
        virtual int foo(void) = 0;
};

IBuildConfiguration& BCInstance(void);

#endif /* IBUILD_CONFIGURATION_H */

And the following concrete class:

BuildConfiguration.h

#ifndef BUILD_CONFIGURATION_H
#define BUILD_CONFIGURATION_H

class BuildConfiguration : public IBuildConfiguration
{
    public:

        BuildConfiguration();
        ~BuildConfiguration();

        virtual int foo(void);
};

#endif /* BUILD_CONFIGURATION_H */

BuildConfigration.cpp

BuildConfiguration::BuildConfiguration()
{
    // init stuff
}

BuildConfiguration::~BuildConfiguration()
{
    // destroy stuff
}

int BuildConfiguration::foo(void)
{
    return 382000; //just for fun
}

// Singleton initialization function
IBuildConfiguration& BCInstance(void)
{
    static BuildConfiguration instance = BuildConfiguration();
    return instance;
}

Now, I'm trying to use the object as follows:

MyClass.h

#include "IBuildConfiguration.h"

class MyClass
{
    private:
        IBuildConfiguration& oFoo;

    public:
        MyClass();
};

MyClass.cpp

MyClass::MyClass()
{
    oFoo = BCInstance();
}

Unfortunately, this results in the compiler error 'oFoo' : must be initialized in constructor base/member initializer list and I can't figure out what's going on. Thanks

To add to what others have already indicated, the class members will already be created (through their default constructor) when the program enters the constructor body. Hence, any initialization within the class body will invoke the assignment constructor as the object would have already been created.

Now, since a reference cannot be re-initialzed, assigning a reference within the constructor body would mean re-initialization and hence the compiler flags an error asking you to initialize the reference in the constructor initialization list. The same goes while initializing const members and members of class that do not have a default constructor.

Follow error message indication:

MyClass::MyClass() : oFoo(BCInstance())
{
}

You can't modify what a reference refers to. You can only initialize it:

MyClass::MyClass() : oFoo(BCInstance())
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM