Similar to: How can I initialize base class member variables in derived class constructor?, but I was wondering why if I have:
class A {
public:
A(int val);
virtual int get_val() = 0;
protected:
int val;
};
class B : public A {
public:
B(int val, int extra);
int get_val() = 0;
private:
int extra;
};
I'm wondering what is the difference between doing this:
A::A(int val) : val(val) {}
and:
A::A(int val) {val = val;}
And also why, when I'm in the constructor for class B, I can't do:
B::B(int b, int extra) : A(b) {
extra = extra;
}
But I can do:
B::B(int b, int extra) : A(b) {
this->extra = extra;
}
or,
B::B(int b, int extra) : A(b), extra(extra){}
to store the value of extra in B. If I don't do those it's not stored. I'm very confused what's happening.