Analyzing Execution of C++ Code

The second type of interview questions in C++ concerns analyzing execution results of some sample code. Candidates without deep understanding of C++ are prone to make mistakes because the code to be analyzed is usually quite tricky.
For example, an interviewer hands a piece of paper printed with the code in Listing 2-8 to a candidate and asks the candidate what the result is if we try to compile and execute the code: (A) Compiling error; (B) It compiles well, but crashes in execution; or (C) It compiles well, and executes smoothly with an output of 10.
Listing 2-8. C++ Code about Copy Constructor
class A {
int value; 

    A(int n) {
value = n; }
    A(A other) {
        value = other.value;
    void Print() {
         std::cout << value << std::endl;
int main(int argc, _TCHAR* argv[]) {
    A a = 10;
    A b = a;
return 0; }
The parameter in the copy constructor A(A other) is an instance of type A. When the copy constructor is executed, it calls the copy constructor itself because of the pass-by-value parameter. Since endless recursive calls cause call stack overflow, a pass-by-value parameter is not allowed in the C++ standard, and both Visual Studio and GCC report an error during compiling time. We have to modify the constructor as A(const A& other) to fix this problem. That is to say, the parameter in a copy constructor should be passed by a reference. appreciates your contribution please mail us the questions you have to so that it will be useful to our job search community

No comments:

Top Blogs