const reference must be initialized in constructor base/member initializer list

18,385

Solution 1

don`t declare default constructor. It is not available anyway (automatically that it's) if you declare your own constructor.

class CBar
{
public:
    CBar(const CFoo& foo) : fooReference(foo)
    {
    }
private:
    const CFoo& fooReference;
};

fairly comprehensive explanation of constructors can be found here: http://www.parashift.com/c++-faq-lite/ctors.html

Solution 2

The easiest way to create the default constructor you don't wanna use (that is the case with your constructor, is that right?) is just not defining it, that is:

class CBar
{
public:
    CBar(const CFoo& foo) : fooReference(foo)
    {
    }

    ~CBar();

private:
    const CFoo& fooReference;

    CBar();
};

In this case, it may be a little superfluous, because the compiler will not create a default constructor for a class with a reference member, but it's better to put it there in case you delete the reference member.

Share:
18,385
Trevor Balcom
Author by

Trevor Balcom

I'm a computer programmer from the United States specializing in mobile development in the transportation industry.

Updated on June 04, 2022

Comments

  • Trevor Balcom
    Trevor Balcom about 2 years

    I am trying to block access to the default constructor of a class I am writing. The constructor I want others to use requires a const reference to another object. I have made the default constructor private to prevent others from using it. I am getting a compiler error for the default constructor because the const reference member variable is not initialized properly. What can I do to make this compile?

    class CFoo
    {
    public:
        CFoo();
        ~CFoo();
    };
    
    class CBar
    {
    public:
        CBar(const CFoo& foo) : fooReference(foo)
        {
        }
    
        ~CBar();
    
    private:
        const CFoo& fooReference;
    
        CBar() // I am getting a compiler error because I don't know what to do with fooReference here...
        {
        }
    };
    
  • Trevor Balcom
    Trevor Balcom almost 14 years
    Thank you for the help. For some reason, I thought the compiler generated a default constructor even if I did not write one.
  • Admin
    Admin almost 14 years
    @Trevor It does, provided you don't explicitly declare a constructor (of any kind) in your class definition.
  • rwong
    rwong almost 14 years
    @Trevor You may also need to block the copy constructor as well.