Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if i create an object in destructor, what will happen?

Tags:

c++

destructor

#include <iostream>
using namespace std;

class teacher{
private:
    int Tnum;
public:

    teacher(){
        Tnum = 0;
    }
    teacher(int n){
        cout << "creating teacher"<<endl;
        Tnum = n;
    }
    ~teacher(){
        cout << "destroying teacher" << endl;

    }   
};

class student: public teacher{

private:
    int Snum;

public:
    student(){
        Snum =0;
    }

    student(int n){
        cout << " creating student"<<endl;
        Snum = n;
    }
    ~student(){
        cout << "destroying student"<<endl;
       teacher t(1);
      cout << "teacher created"<<endl;
    }
};

int main(){

    teacher t(20);
    student s(30);

}
like image 820
ahmad iqbal Avatar asked Oct 18 '25 15:10

ahmad iqbal


1 Answers

You showed an example that compiles. What happens?
It behaves just like an object created in any other function, and it will be destroyed once it goes out of scope.

From 12.4p8 we find that:

After executing the body of the destructor and destroying any automatic objects allocated within the body [...]

This confirms that creating objects in the body of the destructor is legal.

But, be careful! It could hurt you if the constructors of those objects throw exceptions, because destructors are non-throwing and encountering an exception would result in the termination of the application.

like image 154
skypjack Avatar answered Oct 21 '25 06:10

skypjack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!