tags:

views:

362

answers:

2

I have written this small code snippet in C++, the output is also attached. I fail to understand why the constructor is being called only once, while i can see two calls being made for destructor.

From what i understand, default constructor and overloaded assignment operator should be called at line 28.

Can someone please throw some light on this:

  1 #include <iostream>
  2 using namespace std;
  3 
  4 class ABC {
  5   char c;
  6   public:
  7     ABC() {
  8       cout << "default" << endl;
  9     }
 10     ABC(char c) {
 11       this->c = c;
 12       cout << c << endl;
 13     }
 14     ~ABC() {
 15       cout << hex << this << " destructor " << c << endl;
 16     }
 17     void method() {
 18       cout << "method" << endl;
 19     }
 20     void operator= (const ABC& a) {
 21       cout << "operator" << endl;
 22     }
 23
 24 };
 25 
 26 int main() {
 27   ABC b('b');
 28   ABC a = b;
 29 }


Output in g++ version 4.0.1:
~/src$ g++ test.cpp
~/src$ ./a.out 
b
0xbffff0ee destructor b
0xbffff0ef destructor b
+13  A: 
ABC a = b;

This is a copy constructor not the assignment operator! you could redefine it like this what you have is compiler-generated one :

ABC(const ABC& other)
{
 c = other.c;
 cout << c << " copy constructor" << endl;
}


If you really insist on not using a copy constructor you can add converstion operator like to your class and forget the copy constructor!

operator char()
{
  return c;
}
AraK
Even better, you could use an initialisation list.
anon
Yeah as it is now, the copy constructor contains a call to the assignment operator of `c` in your code
Johannes Schaub - litb
@litb that is true lol :)
AraK
Yeah, this works. Thanks @AraK
lava
Make sure you don't do the conversion operator, I mentioned it just for fun, it is not for this case :)
AraK
+7  A: 

The code you have just call the copy constructor, this is the definition:

ABC(const ABC& a):c(a.c){
    cout << "copying " << hex << &a << endl;
}

And you shoud see output like this:

b
copying 0x7fffebc0e02f
0x7fffebc0e02e destructor b
0x7fffebc0e02f destructor b

If you want to call default constructor and then the assignment operator you must use two separate statement:

  ABC b('b');
  ABC a;
  a = b;
lionbest