C++ recap: constructors, destructors, encapsulation

A series of short recaps of learncpp.
Implementation example of a rudimental string library.

#include <iostream>
#include <cstring>

class myString 
{
  /* everything is private by default */
private:
  char *string;
  int length;

public:
  // constructor
  myString(const char *new_string) {
    this->length = strlen(new_string) + 1;
    this->string = new char[length];
    strncpy(string, new_string, length);
    this->string[length -1] = '\0';
  }

  // destructor: no args, no return
  ~myString() {
    delete this->string;
    this->string = NULL;
  }

  /* encapsulation: making all the member variables
     private, and providing public access functions
     to work with the class */

  // getters
  char *getString() { return this->string; }
  int getLength() { return this->length; }
};


int main() 
{
  using namespace std;

  myString aString("Not so funny");
  cout << " -> " << aString.getString() << endl;
  cout << " -> " << aString.getLength() << endl;
  
  return 0;
}
|