I am compiling a class, the complete program to which is given below:
#include<iostream>
using namespace std;
class Test{
public:
Test()
{
cout<<"Test variable created...\n";
// accessing width variable in constructor
cout<<"Width is "<<width<<".\n";
}
void setHeight(int h)
{
height = h;
}
void printHeight()
{
cout<<"Height is "<<height<<" meters.\n";
}
int width = 6;
protected:
int height;
};
int main()
{
Test t = Test();
t.setHeight(3);
t.printHeight();
return 0;
}
The code works absolutely fine, but how is the constructor able to access the variable width
which has not been declared until the end of public
block. Also, how are the member functions able to access the variables declared later in the public block? Isn't C++ sequential (executing the statements in the order they are written)?
int height{};
so that users can't invoke undefined behaviour by trying toprintHeight()
without havingsetHeight()
.int width = 6;
) before the constructor is called. That means that the structure of the class has to be known before the first non-static method can be called.