Unable to use "received" for its base base class "base"

I encounter an error when trying to create an object that inherits from a class that inherits from a class that defines pure virtual functions. I'm not sure what happened. I know that I need to override pure virtual functions in my derived class, but it does not work. I just want to override the function in the ProduceItem class, not the Celery class, because I want the Celery class to inherit overridden methods from ProduceItem.

In the main:

GroceryItem *cel = new Celery(1.5); //Cannot cast 'Celery' to its private base class GroceryItem class GroceryItem { public: virtual double GetPrice() = 0; virtual double GetWeight() = 0; virtual std::string GetDescription() = 0; protected: double price; double weight; std::string description; }; 

ProduceItem Header File:

 #include "GroceryItem.h" class ProduceItem : public GroceryItem { public: ProduceItem(double costPerPound); double GetCost(); double GetWeight(); double GetPrice(); std::string GetDescription(); protected: double costPerPound; }; 

File ProduceItem.cpp:

 #include <stdio.h> #include "ProduceItem.h" ProduceItem::ProduceItem(double costPerPound) { price = costPerPound * weight; } double ProduceItem::GetCost() { return costPerPound * weight; } double ProduceItem::GetWeight() { return weight; } double ProduceItem::GetPrice() { return price; } std::string ProduceItem::GetDescription() { return description; } 

Celery Header Title:

 #ifndef Lab16_Celery_h #define Lab16_Celery_h #include "ProduceItem.h" class Celery : ProduceItem { public: Celery(double weight); double GetWeight(); double GetPrice(); std::string GetDescription(); }; #endif 

File Celery.cpp:

 #include <stdio.h> #include "Celery.h" Celery::Celery(double weight) : ProduceItem(0.79) { ProduceItem::weight = weight; description = std::string("Celery"); } 
+8
c ++ inheritance
source share
2 answers

Here you use personal inheritance: class Celery : ProduceItem . The default inheritance level for class es is private .

Change it to class Celery : public ProduceItem

Note that when you delete this pointer, you will be a memory leak, because you do not have virtual destructors. Just add these definitions to your classes:

 virtual ~GroceryItem() {} 
+18
source share

Class inheritance is private by default. Usually, and in your case you want public inheritance. So:

 class Celery : public ProduceItem 

And similarly on class ProduceItem .

Note that for structs, inheritance is public by default (you can say struct Foo : private Bar if you want).

+3
source share

All Articles