Skip to content

Instantly share code, notes, and snippets.

@iarash84
Created March 7, 2023 07:38
Show Gist options
  • Save iarash84/c5f6a3d1f43cc95c8be01869cdba97d5 to your computer and use it in GitHub Desktop.
Save iarash84/c5f6a3d1f43cc95c8be01869cdba97d5 to your computer and use it in GitHub Desktop.
operator overloading example
#include <iostream>
#include <string>
class MyString {
public:
MyString() : m_data("") {}
MyString(const std::string& data) : m_data(data) {}
MyString operator+(const MyString& other) const {
return MyString(m_data + other.m_data);
}
friend std::ostream& operator<<(std::ostream& os, const MyString& str);
private:
std::string m_data;
};
std::ostream& operator<<(std::ostream& os, const MyString& str) {
os << str.m_data;
return os;
}
int main() {
MyString str1("Hello, ");
MyString str2("world!");
MyString result = str1 + str2; // Operator+ called
std::cout << result << std::endl; // Operator<< called
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment