I have a hierarchy of classes. The base class uses some tuning parameters that are loadable from file (and reloadable during runtime). Each derived class may add some additional parameters. I am looking for a way to allocate a correctly sized parameters array in the base constructor, so that I don't have to deallocate and reallocate in the derived class. I was hoping for something like this, but it's not working (parameters always has 2 elements):
class Base
{ static int nParms;
virtual int getNParms() { return nParms;}
float *parameters;
public:
Base()
{ parameters= new float[this->getNParms()];
parameters[0] = globalReloadableX;
parameters[1] = globalReloadableY;
}
};
int Base::nParams =2;
class Derived : public Base
{ static int nParms;
virtual int getNParms() { return nParms;}
public:
Derived() : Base()
{ parameters[2] = globalReloadableZ;
}
}
int Derived::nParams =3;
I've seen this question, but the solution there doesn't quite work for me. I also tried making parameters a regular array in each class:
class Base
{ float parameters[2]
...
class Derived : public Base
{ float parameters[3]
...
but that makes Derived have 2 separate arrays.
Any ideas?
How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++
To pass arguments to a constructor in a base class, use an expanded form of the derived class' constructor declaration, which passes arguments along to one or more base class constructors. Here, base1 through baseN are the names of the base classes inherited by the derived class.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
Easy explanation - The constructor must be having the same name as that of a class. Hence a constructor of one class can't even be defined in another class. Since the constructors can't be defined in derived class, it can't be overloaded too, in derived class.
Why not pass the required array size as a parameter in the constructor of the base class?
(The reason the virtual function doesn't call the derived class is because that is how C++ virtual functions work; conceptually, until the derived class constructor completes, the object's type is still the base class.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With