How to fix derived class giving 'declaration has no storage class or type specifier' error?

Viewed 2615

I am trying to initialize a base class variable in a derived class, but instead, I am given an error:

 "this declaration has no storage class or type specifier"

I have been tinkering with C++ inheritance and derived classes in Visual Studio. I made the main class "Food" with protected variables and want to derive a class "Bread"

When trying to initialize said variables in "Bread," VS gives an error. I feel like this is a really simple problem that I somehow missed.

#include <string>
using namespace std;

class Food 
{
protected:
    string name;
    int cost;
    int calories;

public:
    Food(string name, int cost, int calories) {
    }
};

class Bread : public Food 
{
private:
    name = "";
    cost = 5;
    calories = 200;
public:

};

I would except the variables of Bread to be initialized: name as "" (empty), cost as "5", calories as "200".

The output is instead an error:

"this declaration has no storage class or type specifier"
1 Answers

I'm trying to initialize a base class variable in a derived class!

First of all, initialize the members in the base class Food's constructor, which you have provided.

Food(std::string name, int cost, int calories)
    : name{ name }
    , cost{ cost }
    , calories{ calories }
{}

Then, you need to initialize the base class members in the constructor member initializer list of the derived class Bread:

class Bread : public Food 
{
public:
    Bread()
        :Food{ "", 5, 200 }
    {}
};

which will initialize the Food members

name = ""
cost = 5
calories = 200
Related