Calling constructor from a constructor

Jul 9, 2010 at 12:19am
Hi everyone,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
	myLinkedList ( )  {                                                         //TESTED
                 head = NULL;
                 last = NULL;
                 cout<<"Linked List is created with default constructor\n";
}

	
	myLinkedList ( myLinkedList &arr) {                                        //TESTED
                 if (arr.head == NULL){head=NULL; last=NULL;}
                 else{
                      head = NULL;
                      last = NULL;
                      temp2 = new node;
                      temp2 = arr.head;
                      while(temp2!=NULL){
                                        insertLast(temp2->item);
                                        temp2 = temp2->next;
                      }
                 }
                 cout<<"Linked List is created with copy constructor\n";
}
	
	// Delete the internal variables as required
	~myLinkedList () {                                                         //TESTED
                  while (head!=NULL)
                        deletee(1);
                  cout<<"Linked List is deallocated!!\n";
}


and in my other class' constructor i wanted to call copyconstructor:
1
2
3
4
5
6
7
8
class dynamicArr {
private:
    myLinkedList data;
public:
	// CONSTRUCTORS
	dynamicArr ( ) {}
	dynamicArr ( dynamicArr& arr) {myLinkedList(arr.data);}
	~dynamicArr ( ) {data.~myLinkedList();}


and my full main method:
1
2
3
4
5
6
7
8
9
10
11
12
	
	dynamicArr B();
	B.insert(4);
	B.insert(6);
	B.insert(2);
	cout<<"error";
	dynamicArr C(B);
	cout<<"error";
	C.print();
	C.~dynamicArr();
	system("PAUSE");
    return 0;

but look out the outputs. As you see when i call "dynamicArr ( dynamicArr& arr)", it also goes into destructor and default constructor so why is that and what is the solution?
outputs
Linked List is created with default constructor
errorLinked List is created with default constructor
Linked List is created with copy constructor
Linked List is deallocated!!
errorThe Linked List is empty!!
Linked List is deallocated!!
Linked List is deallocated!!
Jul 9, 2010 at 12:34am
data.~myLinkedList();
C.~dynamicArr();
No! No! No! No! No!

1
2
3
4
5
6
7
8
9
10
11
struct A{
    int a;
    A(int b){
        this->a=b;
    }
};

struct B{
    A a;
    B():a(10){}
};
Jul 9, 2010 at 1:03am
I didn't understand anything. Could you please state which lines should change with these lines?
Jul 9, 2010 at 3:17am
You NEVER call the destructor yourself (except in cases that you need not concern yourself with). Where did you get the idea that you should?
Automatic objects are always destroyed at the end of their scope, which also means their destructor is called.
If you have a pointer to an object that was allocated on the free store, use the delete operator.
Topic archived. No new replies allowed.