Rotating a linked list around pivot
October 20, 2012
Factory Design Pattern
October 23, 2012

Output of C++ program

What will be the output of below C++ program?

class A
{
  public:
    A& operator=(const A& a)
    {
        cout << "Inside Overload Assignment Operator." << endl;
        return *this;
    }
};
class B
{
  private:
    A objA[5];
};
int main()
{
    B obj1, obj2;
    obj1 = obj2;
}

Answer:

The output will be

Inside Overload Assignment Operator.
Inside Overload Assignment Operator.
Inside Overload Assignment Operator.
Inside Overload Assignment Operator.
Inside Overload Assignment Operator.

We are assigning an object of class B to another object of the same class. Hence, assignment operator for class B will be called.

Now, we have not overloaded assignment operator for class-B. Hence, the default assignment operator (supplied by the compiler) will be called.

Note: C++ also provides Default Assignment operator, the way it provides Default Copy Constructor (and Default Constructor). The Default Assignment Operator function does a member-wise copy for each member of the class.

The class B has only one member, i.e objA, which is an Array of 5 elements.

Hence each element of the array objA of object obj2 will be assigned to corresponding element in obj1. The overloaded assignment operator in Class-A will be called 5 times, Hence the output.

Leave a Reply

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