Answer to Question #102012 in C++ for Fardeen Shaikh

Question #102012
Define a class Message with two data members, one character pointer and an integer storing length. Overload operator binary + to represent concatenation of messages.
1
Expert's answer
2020-01-31T07:53:35-0500

#include <iostream>

#include <cstring>

using namespace std;

/*

g++ prog.cc -Wall -Wextra -std=gnu++17

*/

class Message {

public:

Message() = default;

Message(const char* text) {

m_length = strlen(text);

m_text = new char[m_length];

strcpy(m_text, text);

}

Message(const Message&) = delete;

Message& operator=(const Message&) = delete;

Message(Message&&rsh) {

m_text = rsh.m_text;

m_length = rsh.m_length;

rsh.m_text = nullptr;

rsh.m_length = 0;

}

Message& operator=(Message&&rsh) {

if( this == &rsh)

return *this;

m_text = rsh.m_text;

m_length = rsh.m_length;

rsh.m_text = nullptr;

rsh.m_length = 0;

return *this;

}

~Message(){

if(m_text!= nullptr) {

delete [] m_text;

}

}

friend Message operator+(const Message& lsh, const Message& rsh) {

Message result;

result.m_length = lsh.m_length + rsh.m_length;

result.m_text = new char[result.m_length];

strcpy(result.m_text, lsh.m_text);

strcpy(result.m_text + lsh.m_length, rsh.m_text);

return result;

}

void Print() const {

cout<<"Text: "<<m_text<<"; length: "<<m_length<<endl;

}

private:

char * m_text { nullptr };

int m_length { 0 };

};

int main()

{

Message lsh("hello "), rsh("world!");

(lsh+rsh).Print();

(Message("another one") + Message(" and another one!")).Print();

return 0;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS