class Base
{
public:
Base(int a, string b) : Score(a), Name(b) {}
~Base();
void SetScore(int Points) const { Score += Points; }
int GetScore() { return Score; }
string GetName() { return Name; }
protected:
int Score;
string Name;
};
class Child : public Base
{
public:
Child(int a, string b) : Score(a), Name(b) {}
~Child();
void SetWinner(bool Answer) const { Winner = Answer; }
bool GetWinner() { return Winner; }
};
int main()
{
Base Thing(0, "Guy");
cout << Thing.GetName() << ' ' << Thing.GetScore();
Child Thing2(20, "Gus"); // <--- Can I do this!
cout << Thing2.GetName() << ' ' << Thing2.GetScore();
Thing2.SetWinner(true);
cout << "\n\n" << Thing2.GetName() << " beats " << Thing.GetName() << "!\n\n";
return 0;
}
Basically I know that I can use the Base class's functions and I can overload them if I make them virtual, but in my program when I try to use protected variables in the Base class in my derived class's constructor, it says that those variables aren't in the derived class. Like:
class 'Child' does not have any field named' Score'.
It's just that you cannot list the base class members in the constructor initialization list. Instead you can use the base class constructor Child(int a, string b) : Base(a, b) {}
A class can only initialize its own members in its initializer list. Score and Name are not members of Child, they are members of Base.
The best way to do this is to call the appropriate Base constructor from Child's initializer list:
1 2 3
//Child(int a, string b) : Score(a), Name(b) {} // bad
Child(int a, string b) : Base(a,b) { } // good
EDIT: Anyway, the answer to your topical question is "yes". Derived classes can access protected base class members... just not in the initializer list.
Huh, that seems like strange syntax and I've never come across it before. It works though, so thanks for the help guys. I thought I was going insane, but I just haven't used the variables anywhere other than in the initializer list, so..