C++ Classes Constructor

Greetings, I was checking Unit 5 from this course, and I had a question while seeing the use of the constructor of a class

If I understood correctly, you would need to define first the variables before asigning a value to it, so how is the constructor working if the definition of the variables name, age and height is being done on future lines? Or is the constructor being executed after all the “public” tag lines are done? Thanks from advance!


You have asked a valid question and the answer is quite long for that. Mainly referring to C++ coding methods and practices, but I will give you a concise explanation.

The variables and the constructor are present inside the same scope (public) inside the Hobbit class.
During compile-time, C++ compilers will internally store the variables and constructor functions in the memory in the proper sequential order.

Therefore, when you are inside a class and within the correct scope, you can define the variables, functions (methods) and the constructor (which is yet another function) anywhere you want.

In a non-classed version of the program, what you said will hold true, since you need to define the variables before the program’s main function begins. But in case of an object-oriented program, the scope operator takes care of the definitions of the variables, functions, constructor and destructors during compile time. This will not cause any problems.

I hope that is clear to you. If you need more explanation, refer to C++ reference website on OOPS concepts and classing.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.