Reputation: 13
Currently learning more c++ and I have this question: Why do I have to use a function to change a member of a parent class instead of just changing it without the function?
class Shape{
private:
int a;
protected:
int b;
public:
int c;
};
class Rectangle: public Shape{
public:
c = 123;
void change_c(){c = 321;}
};
Upvotes: 1
Views: 91
Reputation: 598434
Assigning a value to a variable, like in the statement c = 123;
, is illegal outside of a variable declaration or an assignment performed within a function. Which means you can't perform it from within the class scope of a derived class:
class Rectangle: public Shape{
public:
c = 123; // <-- illegal
int d = 123; // <-- OK, in C++11 and later
Rectangle() { c = 321; } // <-- OK
void change_c(){ c = 321; } // <-- OK
}
Upvotes: 1