Code Notes: Introduction to C++, part 2

Topics covered: this pointer, memory allocation

Link to source code: http://www.cs.tufts.edu/comp/15/examples/CPP/ex2.cpp

#include <iostream>

using namespace std;

/*
1. this pointer
*/

class MyClass
{
public:
  // Constructor
  // MyClass(/* MyClass * const this */) = default; // C++11
  MyClass() { cout << "creating MyClass" << endl; }
  
  // Destructor
  // ~MyClass(/* MyClass * const this */) = default; // C++11
  ~MyClass() { cout << "destroying MyClass" << endl; }

  void setData(/* MyClass * const this, */ int d)
  {
    mData = d; // this->mData = d;
  }

  int getData(/* MyClass const * const this */) const
  {
    return mData;
  }
  
private:
  int mData;
};

/* 
2. Memory allocation
 */

int main()
{

  // Static allocation of object

  MyClass m;
  m.setData(5); // MyClass::setData(&m, 5)

  cout << "data = " << m.getData() << endl; // MyClass::getData(&m)

  // Dynamic allocation

  MyClass* m2 = new MyClass();
  m2->setData(6);
  
  cout << "data = " << m2->getData() << endl; // MyClass::getData(&m)

  delete m2; // forgetting this will cause memory leak

  // Defining array of classes

  MyClass* m3 = new MyClass[10]; // Calls the default constructor 10 times

  for (int i = 0; i < 10; ++i) {
    m3[i].setData(i);
  }

  for (int i = 0; i < 10; ++i) {
    cout << "data = " << m3[i].getData() << endl;
  }

  delete [] m3; // Forgetting this causes memory leak

  // Using m3 here will cause dangling pointer access.

  return 0;
} // m destroyed here