0

Can anyone explain me when the C++ destructor class called? When is it automatically called and when does it need to be called explicitly? I have tried following code but it gave unexpected result.

class V{
    private:double x,y,z;
    public:
        V(){
            x=y=x=0.0;
        }
        V(double x=0.0,double y=0.0,double z=0.0):z(z){
            this->x=x;
            (*this).y=y;
            return;
        }
        V(const V &src){
            x=src.x;
            y=src.y;
            z=src.z;
            return;
        }
        void print(){
            cout<<x<<" "<<y<<" "<<z<<endl;
        }
        ~V(){
            cout<<"Destructor called"<<endl;
        }
};
int main(){ 
    V *p;
    p=new V(1,2,3);
    /*delete p;
    Why is the destructor not called automatically for dynamically allocated object p after the program ends? If delete p is included destructor is called. Why is it so?*/   

    V(1,2,3).print();
    /*Here the object does not have any name but still the destructor is called. Why does this happen?*/

    V vec3(V(1,2,3));
    /*Here only one destructor was called but I was expecting two.One for object object **vec3** and other for the nameless object  **V(1,2,3)** as in above case. Why did this happen?*/
}
Saurav Shah
  • 53
  • 1
  • 7
  • Also, you should get a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn form it. – Yksisarvinen Jun 15 '19 at 17:11
  • 1
    For last one you (might (before C++17)) have copy-elision so basically only `V vec3(1,2,3)`. – Jarod42 Jun 15 '19 at 17:14

0 Answers0