Close stream in destructor : destructor « Class « C++ Tutorial






#include <fstream>
#include <iostream>
using namespace std;

class MyClass
{
private:
       char msg[20];
       int loopcounter;
       fstream myfile;
       
public:
  void display(); 
  MyClass();
  ~MyClass();
};

MyClass::MyClass()
{
       myfile.open("input.txt",ios::in);
       myfile.getline(msg,20);

}

MyClass::~MyClass()
{
  myfile.close();
}

void MyClass::display()
{
         cout << msg << "\n";
}

int main() {

       MyClass obj;
       obj.display();
       return 0;
}








9.3.destructor
9.3.1.A simple constructor and destructor.
9.3.2.Close stream in destructor
9.3.3.virtual destructor methods
9.3.4.Demonstrating the order in which constructors and destructors are called.