Predict the output of following C++ programs.
Question 1
#include <iostream> using namespace std;
class A
{ public :
A& operator=( const A&a)
{
cout << "A's assignment operator called" << endl;
return * this ;
}
}; class B
{ A a[2];
}; int main()
{ B b1, b2;
b1 = b2;
return 0;
} |
Output:
A's assignment operator called A's assignment operator called
The class B doesn’t have user defined assignment operator. If we don’t write our own assignment operator, compiler creates a default assignment operator. The default assignment operator one by one copies all members of right side object to left side object. The class B has 2 members of class A. They both are copied in statement “b1 = b2”, that is why there are two assignment operator calls.
Question 2
#include<stdlib.h> #include<iostream> using namespace std;
class Test {
public :
void * operator new ( size_t size);
void operator delete ( void *);
Test() { cout<< "\n Constructor called" ; }
~Test() { cout<< "\n Destructor called" ; }
}; void * Test::operator new ( size_t size)
{ cout<< "\n new called" ;
void *storage = malloc (size);
return storage;
} void Test::operator delete ( void *p )
{ cout<< "\n delete called" ;
free (p);
} int main()
{ Test *m = new Test();
delete m;
return 0;
} |
new called Constructor called Destructor called delete called
Let us see what happens when below statement is executed.
Test *x = new Test;
When we use new keyword to dynamically allocate memory, two things happen: memory allocation and constructor call. The memory allocation happens with the help of operator new. In the above program, there is a user defined operator new, so first user defined operator new is called, then constructor is called.
The process of destruction is opposite. First, destructor is called, then memory is deallocated.