ahmad iqbal
ahmad iqbal

Reputation: 387

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

#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);

}

Upvotes: 4

Views: 470

Answers (1)

skypjack
skypjack

Reputation: 50548

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.

Upvotes: 3

Related Questions