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

filter_none

editclose

play_arrow

linkbrightness_4code

#include<stdlib.h>

#include<iostream>

usingnamespacestd;

classTest {

public:

void* operator new(size_tsize);

voidoperator delete(void*);

Test() { cout<<"\n Constructor called"; }

~Test() { cout<<"\n Destructor called"; }

};

void* Test::operator new(size_tsize)

{

cout<<"\n new called";

void*storage = malloc(size);

returnstorage;

}

voidTest::operator delete(void*p )

{

cout<<"\n delete called";

free(p);

}

intmain()

{

Test *m = newTest();

deletem;

return0;

}

chevron_right

filter_none

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.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above