Using Constructors and Destructors to Manage Resources (or RAII) - C++ Class

C++ examples for Class:Constructor

Description

Using Constructors and Destructors to Manage Resources (or RAII)

Demo Code

#include <iostream>
#include <string>

using namespace std;

class Socket {//ww  w  . j a  v  a2s .c om
public:
  Socket(const string& hostname) {}
};

class HttpRequest {
public:
  HttpRequest(const string& hostname) : sock_(new Socket(hostname)) {}
  void send(string soapMsg) { cout << soapMsg; }
  ~HttpRequest() { delete sock_; }
private:
  Socket* sock_;
};

void sendMyData(string soapMsg, string host) {
  HttpRequest req(host);
  req.send(soapMsg);
}

int main() {
  string s = "xml";
  sendMyData(s, "www.book2s.com");
}

Result


Related Tutorials