Oct 212012
 
 C++ Tags:  Add comments

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.

vliegen123.nl

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)