c++ - Is it ok to use base class attribute in the initialization list? -
i have class has attribute value depends on attribute base class. base class attribute modified in constructor need value after being modified. tried summarize idea in example:
#include <string> #include <iostream> class { public: int att_a; a(int x) : att_a(x) { att_a++; }; // att_a being modified in constructor of }; class b : public { public: std::string att_b; // att_b different type att_a value obtained att_a b(int y) : a(y), att_b(std::to_string(att_a)) {}; }; int main(int argc, char const *argv[]) { b b = b(3); std::cout << b.att_b << std::endl; return 0; }
i'm using attribute att_a
class a
, modified during it's construction, input function initializes att_b
of class b
. concerns are:
- is way of accomplishing want?
- even though compiles , run, can cause undefined behavior under circumstances?
can cause undefined behaviour?
no.
when using member initialization list, order defined: first base-classes in order, members in order. @ time create member, base classes , previous declared members instantiated. if switch order in constructor, compiler should output warning.
is way of accomplishing want?
since don't tell going classes, can't tell if way, can way if fits needs.
Comments
Post a Comment