Skip to content

Instantly share code, notes, and snippets.

@rootid
Created June 6, 2015 21:50
Show Gist options
  • Save rootid/84a226572c1dcdc11edd to your computer and use it in GitHub Desktop.
Save rootid/84a226572c1dcdc11edd to your computer and use it in GitHub Desktop.
Implentation of String class with rule of three
#include<iostream>
#include<cstring>
//Implentation of String class with rule of three
class String
{
public:
String(const char* args)
: data_(new char[std::strlen(args) + 1]), length_(std::strlen(args))
{
std::strcpy(data_,args);
}
String(const String& that) // copy constructor
{
copyOther();
}
//assignment operator
/*
Handles the following cases
1. Self-assignment
MyClass one;
one = one;
2. Operator must yield result
MyClass one, two, three;
three = two = one;
*/
String& operator=(const String& other) {
if(this != &other) { // To handle self-assignment
clear();
copyOther ();
}
return *this;
}
~String() //destructor
{
clear()
}
//helper function
void copyOther() {
data_ = new char[std::strlen(that.data_) + 1];
std::strcpy(data_, that.data_);
length_ = that.length_;
}
void clear() {
delete[] data_;
}
private :
char* data_;
size_t length_;
//String& operator=(const String&);
//String(const String& that);
};
int main () {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment