13

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();
};
evanhutomo
  • 627
  • 1
  • 11
  • 24
Byron Mihailides
  • 145
  • 1
  • 1
  • 6
  • 8
    Reference and `const` members must be initialized in a member-initialization list. You don't have one (but you're about to). See this question: ["What is this weird colon-member (“ : ”) syntax in the constructor?"](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor). – WhozCraig May 06 '15 at 06:46
  • Why `const` and reference member variables must be initialized in a member-initialization list? For reference member variables because references are basically constants [Once initialized, a reference cannot be changed to refer to another object.](https://en.cppreference.com/w/cpp/language/reference_initialization) For `cosnt` member variables see an example [here](https://www.learncpp.com/cpp-tutorial/8-5a-constructor-member-initializer-lists/) – zardosht Jun 11 '20 at 17:21

1 Answers1

24

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.

Martin Schlott
  • 4,369
  • 3
  • 25
  • 49