Declaring class variables after assigning values ​​to them in C ++

Here I have a class called Shape

 class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; 

It compiles just fine, but how am I allowed to assign width and height values, although I have not declared them previously? How does the compiler know what they are?

0
c ++
source share
2 answers

Basically, the language works as if the class with the inline member function definitions were rewritten by the compiler as

 class Shape { public: void setWidth(int w); void setHeight(int h); protected: int width; int height; }; inline void Shape::setWidth(int w) { width = w; } inline void Shape::setHeight(int h) { height = h; } 

It has a lot of explanatory power in general, but, heads up: it may not be such a good model for nested classes.


General comments:

  • Strive to provide practical interfaces. For example. if setting the width or height of the form updates its presentation on the screen, then if I want to change both, with the current interface, which will cause two screen updates.

  • Instead of attribute settings, consider functions that perform or verify, for example. in this case, the resize function or feature set.

  • protected Data is generally not a good idea. Make it public or private by default unless you have a good reason.

+4
source share

Inside functions, you need to declare a variable before using it.

This is not required for class variables. In fact, for variables and functions defined directly inside the class, the order does not matter at all. Interestingly, this does not apply to types defined within a class.

0
source share

All Articles