Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to initialize a property of a class that holds a reference to another class by passing such a reference as a parameter to the constructor. However I receive an error:

“'TaxSquare::bank' must be initialized in constructor base/member initializer list”. What is wrong in the following code of the classes?

#ifndef TAXSQUARE_H
#define TAXSQUARE_H
#include "Square.h"

class Bank;

class TaxSquare : public Square
{
    public:
      TaxSquare(int, int, Bank&);
      virtual void process();

    private:
      int taxAmount;
      Bank& bank;

};
#endif
#include <iostream>
#include "TaxSquare.h"
#include "Player.h"
#include "Bank.h"
using namespace std;

TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID)
{
  taxAmount = amount;
  bank = theBank;
}
#ifndef BANK_H
#define BANK_H

class Bank
{
public:
  Bank(int, int, int);
  void getMoney(int);
  void giveMoney(int);
  void grantHouse();
  void grantHotel();

private:
  int sumMoney;
  int numOfHouses;
  int numOfHotels;

};

#endif
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are attempting to assign to bank, not initialize it:

TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID)
{
    // These are assignments
    taxAmount = amount;
    bank = theBank;
}

bank is a reference, and therefore it must be initialized. You do so by putting it in the initializer list:

TaxSquare::TaxSquare(int anID, int amount, Bank& theBank)
: Square(anID), taxAmount(amount), bank(theBank)
{}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...