Inherited element from abstract class cannot be initialized by inherited constructor

class CarPart { public: CarPart(): name(""), price(0) {} virtual int getPrice() = 0;//{return price;} protected: int price; string name; }; class Tire: public CarPart { public: virtual int getPrice() {return price;} Tire(): CarPart(), name("Tire"), price(50) {} }; 

Visual 2010 tells me that the name and price are not members of the derivative, but are inherited (error c2614). What am I doing wrong?

+4
source share
4 answers

You cannot initialize members that are not a direct member of your class. n not a direct member of deriv ; it is a direct member of base .

However, n is accessible to deriv , so you can always assign it in your deriv constructor, but you really have to initialize it in the base constructor.

In addition, you cannot have virtual constructors. Did you mean to use virtual destructors?

 class base { public: base() : n(0) {} // Are you sure you don't want this? virtual void show() = 0; protected: int n; }; class deriv : public base { public: deriv() { n = 0; } virtual void show() {} }; 

EDIT (response to OP editing): You do not need virtual methods for this:

 class CarPart { public: CarPart(const char* newName, int newPrice) : name(newName), price(newPrice) {} const std::string& GetName() const { return name; } int GetPrice() const { return price; } private: std::string name; int price; }; class Tire : public CarPart { public: Tire() : CarPart("Tire", 50) {} }; 

Assuming CarPart should be a name and price for all of your CarPart , that should be more than enough.

+8
source

1) n is left uninitialized in the database;

2) virtual deriv(): n(0) {} not a constructor

You probably wanted to:

 class base { public: base(int n) : n(n) {} ... class deriv: public base { public: deriv(): base(0) {} ... 
+2
source

Note. Constructors cannot be virtual!

You cannot initialize members of a base class using member initialization syntax. Or initialize n in the base class (this is the right way to do this):

 class base { public: base(int n_ = 0) : n(n_) {} virtual void show() = 0; protected: int n; }; class deriv: public base { public: deriv() : base(0) {} void show() {} }; 

or assign the value n inside the constructor of the derived class (not good, at least not without initialization in the base class:

 class base { public: base(int n_ = 0) : n(n_) {} virtual void show() = 0; protected: int n; }; class deriv: public base { public: deriv() { n = 1; } void show() {} }; 
+1
source

You cannot initialize a member of a base class in a derived class, since the base class is already constructed before initializing the derived class. You can provide a constructor that takes a parameter for n :

 base(int val) : n(val) {} 

Then pass it to your deriv constructor:

 deriv() : base(0) {} 
0
source

Source: https://habr.com/ru/post/1332515/


All Articles