Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a constructor without creating object

What exactly is happening in the code below.

#include<iostream.h>

class Demo
{
    public :

    Demo()
    {
        cout<<"\nIn Demo const";
    }
    ~Demo()
    {
        cout<<"\nin demo dest";
    }
};

void main() {
    Demo();
}

Demo() simply calls the constructor and destructor. Is a object being created in this process? And thus is the memory being allocated?

like image 936
Shreyas Avatar asked Sep 19 '13 10:09

Shreyas


1 Answers

You're not explicitly calling the constructor, instead this code creates a temporary unnamed object with type Demo, which is destroyed immediately after ;.

Yes, memory is allocated (automatically, on the stack) for this temp object and it's freed (again automatically) after ;. Meanwhile, the constructor and destructor are called, as expected.

like image 121
Kiril Kirov Avatar answered Sep 27 '22 20:09

Kiril Kirov