Open In App

Output of C++ Program | Set 4

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Difficulty Level: Rookie

Predict the output of below C++ programs.

Question 1




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


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




#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;
}


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




#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;
}


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

See following comments for explanation:




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


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



Last Updated : 27 Dec, 2016
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads