Output of C++ Program | Set 4

Difficulty Level: Rookie

Predict the output of below C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
int x = 10;
void fun()
{
    int x = 2;
    {
        int x = 1;
        cout << ::x << endl; 
    }
}
  
int main()
{
    fun();
    return 0;
}

chevron_right


Output: 10
If Scope Resolution Operator is placed before a variable name then the global variable is referenced. So if we remove the following line from the above program then it will fail in compilation.

  int x = 10;



Question 2



filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
class Point {
private:
    int x;
    int y;
public:
    Point(int i, int j);  // Constructor
};
  
Point::Point(int i = 0, int j = 0)  {
    x = i;
    y = j;
    cout << "Constructor called";
}
  
int main()
{
   Point t1, *t2;
   return 0;
}

chevron_right


Output: Constructor called.
If we take a closer look at the statement “Point t1, *t2;:” then we can see that only one object is constructed here. t2 is just a pointer variable, not an object.



Question 3

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
class Point {
private:
    int x;
    int y;
public:
    Point(int i = 0, int j = 0);    // Normal Constructor
    Point(const Point &t); // Copy Constructor
};
  
Point::Point(int i, int j)  {
    x = i;
    y = j;
    cout << "Normal Constructor called\n";
}
  
Point::Point(const Point &t) {
   y = t.y;
   cout << "Copy Constructor called\n";
}
  
int main()
{
   Point *t1, *t2;
   t1 = new Point(10, 15);
   t2 = new Point(*t1);
   Point t3 = *t1;
   Point t4;
   t4 = t3;
   return 0;
}

chevron_right


Output:
Normal Constructor called
Copy Constructor called
Copy Constructor called
Normal Constructor called

See following comments for explanation:

filter_none

edit
close

play_arrow

link
brightness_4
code

Point *t1, *t2;   // No constructor call
t1 = new Point(10, 15);  // Normal constructor call
t2 = new Point(*t1);   // Copy constructor call 
Point t3 = *t1;  // Copy Constructor call
Point t4;   // Normal Constructor call
t4 = t3;   // Assignment operator call

chevron_right


Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.