Code Notes: Introduction to C++, part 3

Topics covered: Size of empty class, 4 auto-generated member functions, namespace

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

#include <iostream>

using namespace std;

// std namespace contains all the standard classes.

namespace EX3 {

class EmptyClass
{
};


/*

4 auto-generated functions:

* Default constructor
* Copy constructor
* Copy assignment
* Destructor

 */

class AnotherClass 
{
};

class MyClass
{
public:
  MyClass();
  MyClass(MyClass const & other);
  MyClass & operator=(MyClass const & other);
  ~MyClass();

private:
  int data1;
  int* data2;
  AnotherClass data3;
};

// Default constructor
MyClass::MyClass()
  : data3()
{
  // data1 and data2 NOT initialized
}

// Copy constructor
MyClass::MyClass(MyClass const & other)
: data1(other.data1)
, data2(other.data2)
, data3(other.data3)
{
}

// Assignment operator
MyClass & MyClass::operator=(MyClass const & other)
{
  data1 = other.data1;
  data2 = other.data2;
  data3 = other.data3;
  
  return *this;
}

// Destructor
MyClass::~MyClass()
{
  data3.~AnotherClass();
}

}

// contains 4 functions

int main()
{
  // EmptyClass e;
  // cout << "size of an empty class = " << sizeof(e) << endl;
  EX3::MyClass m;
}