0

Let's consider the following code:

#include <bits/stdc++.h>
using namespace std;

class Temp
{
public:
    Temp()
    {
        cout<<"Inside constructor.\n";
    }
    ~Temp()
    {
        cout<<"Inside destructor.\n";
    }
};

int main()
{
    Temp();
    return 0;
}

In this code, we are calling constructor explicitly. Now my question is, why would we need to call the constructor explicitly? And why would C++ allow us to do so?

Waliul
  • 35
  • 7
  • 1
    For one, you can use it to pass a temporary object of type `Temp` to a function(assuming that function has a parameter of appropriate type). – Jason Mar 17 '22 at 05:33
  • 1
    It's useful in any context where you need an object of that type and want to create one. – chris Mar 17 '22 at 05:40
  • Eg: `myfunctionTakesString(std::string("MyArgs"))`. – Louis Go Mar 17 '22 at 05:45
  • 4
    Also `#include ` and `using namespace std;` are not good ideas. See [this](https://stackoverflow.com/a/31816096/4123703) and [this](https://stackoverflow.com/q/1452721/4123703) – Louis Go Mar 17 '22 at 05:47

0 Answers0