I have created a class of MyString. My code was working just fine but when I wrote the destructor for my class it is giving me the error at delete keyword. Please help me out where is the problem and what is the solution.
MyString Header File
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
class MyString
{
private:
char* str;
int length;
public:
MyString();
MyString(const char*);
~MyString();
};
#endif
MyString CPP File
#include "MyString.h"
#include <iostream>
using namespace std;
MyString::MyString() {
length = 0;
str = new char[length];
str[length] = '\0';
}
MyString::MyString(const char* cString) {
length=strlen(cString);
str = new char[length];
for (int i = 0; i < length; i++)
str[i] = cString[i];
str[length] = '\0';
}
MyString::~MyString() {
delete[] str;
str = nullptr;
length = 0;
}
Main CPP File
#include "MyString.h"
#include <iostream>
using namespace std;
int main() {
//MyString s1;
MyString s2("OOP is Fun!!");
char name[15] = "Pakistan";
MyString s3(name);
return 0;
}