Starting from a base class, I want to create some derived classes, which differs from one another for the value of a number of data members. These different attributes are used in the BaseClass constructor to inizialize other data members. Below you can find a simplified example of what I mean;
class BaseClass {
public:
BaseClass(int a, double b, int c, std::string d) {
// Do stuff depending also on d
}
double f; // Inizialized in the BaseClass constructor
};
class DerivedClass1 : public BaseClass {
public:
DerivedClass1(int a, double b, int c) : BaseClass(a, b, c, d) {};
std::string d = "Hello";
};
class DerivedClass2 : public BaseClass {
public:
DerivedClass2(int a, double b, int c) : BaseClass(a, b, c, d) {};
std::string d = "Goodbye";
};
However, I am surely doing something wrong, since I get
warning: field 'd' is uninitialized when used here [-Wuninitialized]. What is the right way to implement this?
In your given code, i think you missed a point here. in the code:
you have set 4 values in the constructor for the base class.. namely
int a, double b, int c, std::string dThis means whenever you call the constructor of the base class, you are supposed to pass in 4 arguments whereas in this code:in this both class, you have been passing something like a
d(d)which i dont know what is . In other words, just remove thed(d).EDIT: i found you have missed something here as well:
you placed the block of code:
std::string d="Hello";outside the scope of the constructor. Make these changes:and you're good to go. Hope that helps!!!