Calling of destructor?

A

Aneel

What does the calling of destructor at the end of assignment operator
account for? Please see the code below:

#include <iostream>
using namespace std;

class check {
private:
int x;
public:
check(int a=0):x(a){cout<<"\nconstructor\n";}
~check(){cout<<"\ndestructor\n";}
void set_x(int a){x=a;}
int get_x(){return x;}
check operator = (const check &rhs) {
cout<<"\nassignment operator\n";
x = rhs.x;
}

};

int main() {

check ob1, ob2(3);

cout<<"\n\n----------------------\n";
ob1 = ob2;
cout<<"\n------------------------\n\n"; // Destructor is called
before reaching this line, WHY?

system("pause");
return 0;
}
 
S

Saeed Amrollahi

What does the calling of destructor at the end of assignment operator
account for? Please see the code below:

#include <iostream>
using namespace std;

class check {
  private:
    int x;
  public:
    check(int a=0):x(a){cout<<"\nconstructor\n";}
    ~check(){cout<<"\ndestructor\n";}
    void set_x(int a){x=a;}
    int get_x(){return x;}
    check operator = (const check &rhs) {
      cout<<"\nassignment operator\n";
      x = rhs.x;
    }

};

int main() {

  check ob1, ob2(3);

  cout<<"\n\n----------------------\n";
  ob1 = ob2;
  cout<<"\n------------------------\n\n"; // Destructor is called
before reaching this line, WHY?

  system("pause");
  return 0;



}- Hide quoted text -

- Show quoted text -

Hi Aneel
The appropriate decl./def. for copy assignment operator is:
check& operator=(const check &rhs) {
x = rhs.x;
return *this;
}
the following code:
check operator=(const check &rhs) {
x = rhs.x;
return *this;
}
first creates a copy of the object, then returns it.
the destructor is called for that object.
You can test it by declaring copy constructor:
check(const check& c) : x(c.x) { cout<<"\ncopy constructor\n"; }

Cheers,
-- Saeed Amrollahi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top