Output of C++ Program | Set 19
Predict the output of following C++ programs.
Sizeof operator returns the size of string including null character so output is 14. While strlen() function returns the exact length of string excluding null character so output is 13.
Constructor is executed Destructor is executed
The first statement inside the main () function looks strange, but it is perfectly valid. It is possible to create an object without giving its handle to any pointer in C++. This statement will create an object of class Test without any pointer pointing to it. This can be also done in languages like Java & C#.
For example consider following statement:
new student(); // valid both in Java & C#
The above statement will create an object of student class without any reference pointing to it.
Compiler error: 11 8 [Error] expected ';' before 'm'
The above program looks syntactically correct but it fails in compilation. The reason class name. Class name is main so it is necessary to tell the compiler that main is the name of class. Generally struct or class keyword is not required to write to create an object of the class or struct. But when the name of class is main it becomes necessary to write struct or class when creating object of class or struct. Remember main is not a reserved word.
Following is a correct version of the above program:
Now predict the output of following program:
The above program compiles and runs fine because object is global. Global object‘s constructor executes before main() function and it’s destructor executes when main() terminates.
Conclusion: When the class/struct name is main and whenever the local object is created it is mandatory to write class or struct when the object of class / and struct is created. Because C++ program execution begins from main () function. But this rule is not applied to global objects. Again, main isn’t a keyword but treat it as if it were.
This article is contributed Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above