Search code examples
c++oopobject

"Provides no initializer for reference member..."


After some search on google, I cannot find an answer to this error. How do I initialize it, and why do I need to?

#include "CalculatorController.h"


CalculatorController::CalculatorController(SimpleCalculator& aModel, ICalculatorView& aView)
{ \\(this is the bracket informing me of the error)
   fModel = aModel;
   fView = aView;
}

header:

#pragma once

#include  "ICalculatorView.h"
#include "SimpleCalculator.h"

class CalculatorController
{
private:
   SimpleCalculator& fModel;
   ICalculatorView& fView;

public:
   CalculatorController(SimpleCalculator& aModel, ICalculatorView& aView);

   void run();
   ~CalculatorController();
};

Solution

  • Instead of:

    CalculatorController::CalculatorController(SimpleCalculator& aModel, ICalculatorView& aView)
    {\\(this is the bracket informing me of the error)
    
    fModel = aModel;
    fView = aView;
    }
    

    Use

    CalculatorController::CalculatorController(SimpleCalculator& aModel, ICalculatorView& aView) 
     : fModel(aModel),fView(aView)
    {
    }
    

    fModel and fView are reference member. Different instances of CalculatorController can share the same instances fModel and fView this way, without using nasty pointer.

    Reference member have to be initialized on creation. My second code block show how to.