ATL Development   «Prev  Next»
Lesson 15 Coding COM methods 1
Objective Add code to implement IReadPhBook.

Coding COM Methods

We are now ready to code each COM method in IReadPhBook.
Member variable m_currec holds the value of the CurRec property. IReadPhBook::get_CurRec is called to get the value of CurRec; IReadPhBook::put_CurRec is called to set the value of CurRec:

STDMETHODIMP CPhBookObj::get_CurRec
  (long *pVal)
  
{
 *pVal = m_currec;
 return S_OK;
}

STDMETHODIMP CPhBookObj::put_CurRec
  (long newVal)
  
{
  //If newVal is not between 0 and MAX_RECS
  //return an error
    
  if (newVal < 0 || newVal >= MAX_RECS)
  return E_FAIL;
  //If newVal is greater than the number
  //of records in the array
    
  //return an error
  if (newVal >= m_numrecs)
  return E_FAIL;

 m_currec = newVal;
 return S_OK;
}

put_CurRec first checks to see that the new value is between 0 and MAX_REC -1, if not, an error is returned. Next, a check is made to ensure that the new value does not exceed the number of records stored. Technically speaking, E_FAIL is not the best return value we could have used. It would have been better to return an error status as an output parameter.
Property MaxRecs is represented by the MAX_RECS constant. IReadPhBook::get_MaxRecs is implemented as:

Microsoft Visual C++ Windows Applications
STDMETHODIMP CPhBookObj::get_MaxRecs(long *pVal)
{
 *pVal = MAX_RECS;
 return S_OK;
}

Member variable m_numrecs holds the value of property NumRecs. get_NumRecs simply uses this value:
STDMETHODIMP CPhBookObj::get_NumRecs(long *pVal)
{
 *pVal = m_numrecs;
 return S_OK;
}

Method IReadPhBook::GetPhoneRec returns the phone record referenced by the CurRec property (i.e., the value of m_currec) to the caller:
STDMETHODIMP CPhBookObj::GetPhoneRec
  (PhRec *pPhRec, BOOL *pOK)
  
{
   //if the CurRec property is not
   //set we can't get a record
   
 if (m_currec == -1)
 {
  *pOK = FALSE;
 }
 else
 {
  *pPhRec = m_PhRecs[m_currec];
  *pOK = TRUE;
 }
 return S_OK;
}

If m_currec is -1, no phone records are in m_PhRecs; *pOK is set to FALSE to tell the caller a phone record was not returned. Otherwise, the phone record in m_PhRecs referenced by property CurRec (i.e., m_currec) is assigned to pPhRec and *pOK is set to TRUE.

Add Properties Methods to IReadPhBook - Exercise

Click the Exercise link below to apply what you have learned about adding properties and methods to IReadPhBook.
Add Properties Methods to IReadPhBook - Exercise