#include #include using namespace std; int main() { cout << sizeof('GeeksforGeeks') << endl; cout << strlen('GeeksforGeeks'); return 0; }
Output: 14 13Dimensiunea operatorului returnează dimensiunea șirului, inclusiv caracterul nul, astfel încât rezultatul este 14. În timp ce funcția strlen() returnează lungimea exactă a șirului, excluzând caracterul nul, astfel încât rezultatul este 13.
Întrebarea 2: C highllight=12-5
#include using std::cout; class Test { public: Test(); ~Test(); }; Test::Test() { cout << 'Constructor is executedn'; } Test::~Test() { cout << 'Destructor is executedn'; } int main() { delete new Test(); return 0; }
Output: Constructor is executed Destructor is executedThe 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.
Întrebarea 3: C highllight=12-5
#include using std::cout; class main { public: main() {cout << 'ctor is calledn';} ~main() {cout << 'dtor is calledn';} }; int main() { main m; // LINE 11 }
Output: 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: C highllight=12-5
#include using std::cout; class main { public: main() { cout << 'ctor is calledn';} ~main() { cout << 'dtor is calledn';} }; int main() { class main m; }
Now predict the output of following program: C highllight=12-5 #include using std::cout; class main { public: main() { cout << 'ctor is calledn'; } ~main() { cout << 'dtor is calledn'; } }; main m; // Global object int main() { }
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 Faceți cunoștință cu Pravasi .