I have a base and derived class. The base class constructors have some static const variables. Is it okay to use it in derived class constructor to construct base class variable??
an example code will be
//Base.hpp
class Base {
public:
Base(int value_, long sizee_);
private:
int value;
int sizee;
protected:
static const int ONE = 1;
static const int TWO = 2;
static const long INT_SIZE = (long)sizeof(int);
static const long LONG_SIZE = (long)sizeof(long);
};
//Base.cpp
Base::Base(int value_,int sizee_):value(value_),sizee(sizee_) {
}
//Derived.hpp
class Derived: class Base {
public:
Derived();
};
//Derived.cpp
Derived::Derived():Base(ONE+TWO,INT_SIZE+LONG_SIZE) {
}
Here ONE,TWO,INT_SIZE,LONG_SIZE are base class static variables, I will using it to construct the base class itself. Is this approach fine? Please advice.
Yes, it’s fine. By the time you create a
Dervideobject, allstaticmembers are initialized. That is, unless you havestaticDerivedobjects.