0

When i try and create a parameterized constructor for my Vegetable class, I get this error: not a non static data member or base class of class. The error occurs in the Vegetable.cpp file where the constructor is implemented.

Grocery.hpp

#include "Grocery.hpp"          
class Grocery{
public:

    Grocery();
    Grocery(std::string name, double price, double weight);


    bool operator==(const Grocery &rhs) const;      // Comparison operator overload
protected:
    
    std::string name_;
    int quantity_;
    double unit_price_;
    double unit_weight_;
    double total_price_;}; // end Grocery
    #include "Grocery.cpp"
    #endif

Vegetable.hpp

#ifndef Vegetable_
#define Vegetable_

#include "Grocery.hpp"
#include <string>

class Vegetable : public Grocery{
public:
Vegetable(std:: string,double price, double weight );
virtual void updateCost() override;
}

Vegetable.Cpp

#include <iostream>
#include <string>
#include "Vegetable.hpp"

Vegetable ::Vegetable(std :: string name, double price, double weight):name_(name), 
unit_price_(price), unit_weight_(weight){            
}

Error:

"name_" is not a nonstatic data member or base class of class "Vegetable"
"unit_price_" is not a nonstatic data member or base class of class "Vegetable"
"unit_weight_" is not a nonstatic data member or base class of class "Vegetable"

Why is it saying that name_, unit_price_, and unit_weight_ are not members of my vegetable class? didn't i inherit them, and they're protected in the vegetable class?

  • They can be constructed only through calling to constructor of `Grocery`. You can write `Vegetable ::Vegetable(std :: string name, double price, double weight):Grocery(std::move(name), price, weight){ }` – ALX23z Sep 14 '20 at 01:36
  • Why must it only be constructed through the Grocery constructor? What if i had another member variable in Vegetable that wasn't in the Grocery constructor. Then i would need a specific vegetable constructor to account for that unique member variable right? – freehaircuts Sep 14 '20 at 01:44
  • The idea is that your `Vegetable` constructor calls your `Grocery` constructor to initialise the member variables declared in `Grocery`, then initialises any member variables of its own. The idea, I believe, is to enforce proper encapsulation. – Paul Sanders Sep 14 '20 at 01:46
  • Ohhhhhh i get it now. Lets say I had a member variable in Vegetable that Grocery didn't have. Lets call it int myInteger. to include that in the constructor i would do,Vegetable ::Vegetable(std :: string name, double price, double weight):Grocery(name, price, weight) , myInteger(5){ }? – freehaircuts Sep 14 '20 at 01:48
  • Looks good to me. – Paul Sanders Sep 14 '20 at 01:54

0 Answers0