yolin00
yolin00

Reputation: 121

Why using a variable(specially in member function) before declaring in class(c++) don't make a compile error?& how it works?

#include<iostream>

using namespace std;

 class Employee{
    public:
        Employee(char* name,int _year,float _salary)
        {
            emp_name=name;
            emp_join_year=_year;
            emp_salary=_salary;
            Printinfo();
        }
    private:

        int WorkedYear(void)
        {
            //struct date currentdate;
            int YearDiff;
            //getdate(&currentdate);
            YearDiff=2020-emp_join_year;

            return YearDiff;
        }

        void Printinfo(void)
        {
            cout << "Name      :" << emp_name << endl;
            cout << "Join Date :" << emp_join_year << endl;
            cout << "Salary    :" << emp_salary << endl;
            cout << "Worked    :" << WorkedYear() << "year(s)" << endl;
        }

        char* emp_name;
        int emp_join_year;
        float emp_salary;


};


int main()
{
    Employee john("john",1987,12500),mike("mike",1980,15500);
}

here i use emp_name emp_join_year emp_salary in Employee() WorkedYear() of class Employee before declaring (in line) it doesn't make compile error,but if i do this in main function(that is use a variable before / without declaring) it will make a compile error. Why does this happen?

Upvotes: 1

Views: 59

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

A class definition is not considered to be "complete" until its closing brace, at which point the class is completely defined. It's as if all the class methods are defined at that point, together with all the class members, simultaneously. A brief excerpt from the C++ standard:

Class members [class.mem]

A class is considered a completely-defined object type (6.8) (or complete type) at the closing } of the class-specifier . The class is regarded as complete within its complete-class contexts; otherwise it is regarded as incomplete within its own class member-specification.

And the rest of all the moving pieces roll downhill from this point on. This is why it seems that you can use class members in inline class methods before the class members themselves are defined.

Before C++ there was C, and C all variables had to be declared before they are used, and C++ inherited that. There were no class methods in C. And when C++ came about, together with class methods, and many other new things, the original parts of C continued to work as they were, but the new stuff in C++ did not have to work the same way.

Capsule summary: that's how C++ works.

Upvotes: 3

Related Questions