Defining a destructor and the copy constructor - C++ Class

C++ examples for Class:Destructor

Description

Defining a destructor and the copy constructor

Demo Code

#include <iostream>
#include <string>

class Message{/*www.jav  a 2 s.c  o  m*/
private:
  std::string* ptext;                   // Pointer to string

public:
  void show() const{
    std::cout << "Message is: " << *ptext << std::endl;
  }
  // Constructor
  Message(const char* text = "No message")
  {
    ptext = new std::string {text};        // Allocate space for text
  }

  // Copy Constructor
  Message(const Message& message)
  {
    ptext = new std::string(*message.ptext);   // Duplicate the object in the heap
  }

  // Assignment operator
  Message& operator=(const Message& message)
  {
    if (this != &message)
      ptext = new std::string(*message.ptext);  // Duplicate the object in the heap

    return *this;                               // Return the left operand
  }

  // Destructor
  ~Message()
  {
    delete ptext;
  }
};

// Ouput a copy of a Message object
void print(Message message)
{
  message.show();
}
int main()
{
  Message beware {"Careful"};
  Message warning;

  warning = beware;                    // Call assignment operator
  std::cout << "After assignment beware is:\n";
  beware.show();
  std::cout << "After assignment warning is:\n";
  warning.show();
}

Result


Related Tutorials