Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

oop - What is the order of control flow while compiling the code for a class in C++?

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...
";
            // accessing width variable in constructor
            cout<<"Width is "<<width<<".
";
        }
        void setHeight(int h)
        {
            height = h;
        }
        void printHeight()
        {
            cout<<"Height is "<<height<<" meters.
";
        }
        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)?

question from:https://stackoverflow.com/questions/65940862/what-is-the-order-of-control-flow-while-compiling-the-code-for-a-class-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Think of inline definitions in a class as just syntactic sugar for declaring the function, and then defining outside of the class. Manually doing that would transform the code to

class Test{
    public:
        Test();
        void setHeight(int h);
        void printHeight();
        int width = 6;
    protected:
        int height;
};

Test::Test()
{
    cout<<"Test variable created...
";
    // accessing width variable in constructor
    cout<<"Width is "<<width<<".
";
}

void Test::setHeight(int h)
{
    height = h;
}

void Test::printHeight()
{
    cout<<"Height is "<<height<<" meters.
";
}

And you can see from this transformation that the class member is now "before" the function definitions, so there is no reason why they can't know about the variable.

The technical term for this is call the complete-class context and the jist of it is that when you are in the body of a member function or the class member initialization list, the class is considered complete and can use anything defined in the class, no matter where in the class it is declared.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...