Practice Set -4 (C++)

Question 1

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;
}
Show the 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 2

int x = 10;
void fun()
{
    int x = 2;
    {
        int x = 1;
        cout << ::x << endl;
    }
}
 
int main()
{
    fun();
    return 0;
}
Show the 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 3

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 Cunstroctor 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;
}
Show the Output: »

Normal Cunstroctor called
Copy constructor called
Copy constructor called
Normal Cunstroctor 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

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*