Output of C++ Program | Set 17

 

  Predict the output of following C++ programs.

Question 1

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6 public:
 7     A& operator=(const A&a)
 8     {
 9         cout << "A's assignment operator called" << endl;
10         return *this;
11     }
12 };
13 
14 class B
15 {
16     A a[2];
17 };
18 
19 int main()
20 {
21     B b1, b2;
22     b1 = b2;
23     return 0;
24 }

  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

 1 #include<stdlib.h>
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 class Test 
 7 {
 8 public:
 9     void* operator new(size_t size);
10     void operator delete(void*);
11     Test() 
12     { 
13         cout<<"\n Constructor called"; 
14     }
15     ~Test() 
16     { 
17         cout<<"\n Destructor called"; 
18     }
19 };
20 
21 void* Test::operator new(size_t size)
22 {
23     cout<<"\n new called";
24     void *storage = malloc(size);
25     return storage;
26 }
27 
28 void Test::operator delete(void *p )
29 {
30     cout<<"\n delete called";
31     free(p);
32 }
33 
34 int main()
35 {
36     Test *m = new Test();
37     delete m;
38     return 0;
39 }

  Output:

  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.


  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-27  16:44:03

posted @ 2013-11-27 16:44  虔诚的学习者  阅读(166)  评论(0编辑  收藏  举报