C++ Class Definition destructor and the copy constructor

Description

C++ Class Definition destructor and the copy constructor

#include <iostream>
#include <string>

class Message{// w w w  . j  a  v  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();
}



PreviousNext

Related