Member initializer list in derived class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Member initializer list in derived class

#include <iostream> #define Log(x) std::cout << x << std::endl; class A { public: int c; //A():c(5){}; }; class B : public A { public: B() :c(12) {}; }; int main() { B x; Log(x.c); } //So the question is why can't you initialize derived members in the sub class.

27th Feb 2019, 1:48 PM
Akib
Akib - avatar
4 Answers
0
Well, it seems the member initializer list is only for the members of the class to be initzialized. The base class is either initizialized automatically or you do a :A(). And that's also the way to initialize members of A differently in B: #include <iostream> using namespace std; #include <iostream> #define Log(x) std::cout << x << std::endl; class A { public: int c; A(int a = 5):c(a){}; }; class B : public A { public: B() : A(12) {}; }; int main() { B x; Log(x.c); }
27th Feb 2019, 7:57 PM
nobody
0
BTW: Do you know RAII: Resouce Acquisition Is Initializiation. So all members of a (base) shall be initialized after construction.
27th Feb 2019, 7:59 PM
nobody
0
This was bugging me for a while, thanks for answering this.No, I don't know about RAII. If you would explain it a bit more I would love to learn about it. Thanks for the answer.
4th Mar 2019, 5:14 PM
Akib
Akib - avatar
0
wikipedia has a good explanation. Or cppreference.com. they can explain better than i do.
4th Mar 2019, 5:55 PM
nobody