Index

C & C++ Programming - Power of 3

#pragma once
class CExplicit
{
public:
 explicit CExplicit(int i)
 {}
 // Equivalent as above
 //CExplicit(int i)
 //{}
}; /////////////////////////////////////////////////////////////////////////
class CPowerOf3
{
public:
 CPowerOf3(int nLen)
  : m_nLen(nLen)
  , m_pBuf(NULL)
  , m_nRef(m_nLen) // Its mandatory to initial the reference in member initialization list
 {
  cout << __FUNCTION__ << endl;
  m_nRef = m_nLen * 2; // If we changing the reference the original value also changes

  m_pBuf = new int[m_nLen]; // beware int(m_nLen)
  memset(m_pBuf, 0x00, m_nLen*sizeof(int));

  cout << "REF = " << m_nRef << endl;
 }
 ~CPowerOf3()
 {
  cout << __FUNCTION__ << endl;
  if (m_pBuf) {
    delete[] m_pBuf;
    m_pBuf = NULL;
  }
 }

 CPowerOf3(const CPowerOf3& obj)
  : m_nRef (m_nLen)
 {
  cout << __FUNCTION__ << endl;
  if (this != &obj)
  {
   m_nLen = obj.GetLen();
   m_pBuf = new int[m_nLen];
   // Here each byte will initialized with 0XFF
   memset(m_pBuf, 0xFF, m_nLen*sizeof(int));
  memcpy(m_pBuf, obj.GetBuf(), m_nLen*sizeof(int));
  }
 }

 const CPowerOf3& operator = (const CPowerOf3& obj)
 {
  cout << __FUNCTION__ << endl;
  if (this != &obj) {
   m_pBuf = new int[m_nLen];
   // Here each byte will initialized with 0XFF
   memset(m_pBuf, 0xFF, m_nLen*sizeof(int));
   memcpy(m_pBuf, obj.GetBuf(),
    (m_nLen > obj.m_nLen) ? obj.m_nLen*sizeof(int) : m_nLen*sizeof(int));
  }

  return *this;
 }

 int* GetBuf() const
 {
  return m_pBuf;
  }

 int GetLen() const
 {
  return m_nLen;
 }

 void PrintBuf()
 {
  for(int i = 0; i < m_nLen; i++) {
   cout << "Buffer[" << i << "] = " << m_pBuf[i] << endl;
  }
 }

private:
 int* m_pBuf;
 int m_nLen;
 int& m_nRef;
};

void PassByValue(CPowerOf3 x)
{
 cout << __FUNCTION__ << endl;
}

/////////////////////////////////////////////////////////////////////////
void TestPowerof3()
{
 // Will not work as CTOR is explicit
 // CExplicit s2 = 'a';
 // CExplicit s2 = 10;

 //------------------------------------------------------------------
 CPowerOf3 first(10); // initialization by constructor
 CPowerOf3 second(first); // initialization by copy constructor
 CPowerOf3 third = first; // Also initialization by copy constructor
 second = third; // assignment by copy assignment operator


 CPowerOf3 s1(10);
 PassByValue(s1);
 s1.PrintBuf();

 // Single argument CTOR is present so this will call CPowerOf3(int)
 CPowerOf3 s2 = 10;

 s2 = s1;
 s2.PrintBuf();
}
Index