+ 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.
4 ответов
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);
}
0
BTW: Do you know RAII: Resouce Acquisition Is Initializiation. So all members of a (base) shall be initialized after construction.
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.
0
wikipedia has a good explanation. Or cppreference.com. they can explain better than i do.