Blog from Saravanan Arumugam

Let us talk about Technologies

Category Archives: VC++

Conversion function in C++


I was practicing some Visual C++ projects and came across a situation where LPCRECT was assigned just the CRECT object.

I was pretty sure that LP in LPCRECT stands for Long Pointer. But the object I saw in the project was just a non-pointer object.

The code was like this.

class Shape

{

public:

Shape(void)

{

}

virtual ~Shape(void)

{

}

virtual
void Draw(CDC *pDC) = 0;

protected:

CRect m_rc;

};

class Circle : public Shape

{

public:

Circle(void)

{

}

~Circle(void)

{

}

virtual
void Draw(CDC *pDC)

{

pDC->Ellipse(m_rc);

}

};

 

CDC.Ellipse() method takes an LPCRECT type, where it perfectly accommodated CRect.

On researching on the line there is a conversion happening to convert CRect to LPCRECT inside the CRect class. The concept is called Conversion Function.

// convert between CRect and LPRECT/LPCRECT (no need for &)

operator LPRECT() throw();

operator LPCRECT() const throw();

I tried to implement Conversion Function myself in a sample code.

This is what I came up with.

#include
“stdafx.h”

 

typedef
struct

{

public:

    int left;

    int top;

    int right;

    int bottom;

} MyStruct;

 

typedef
const MyStruct *LPStruct;

 

class StructureClass: public MyStruct

{

public:

    StructureClass(void)

    {}

 

    ~StructureClass(void)

    {}

 

    operator LPStruct()

    {

        return
this;

    }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

    LPStruct lpStructure;

    StructureClass cStructure;

 

    cStructure.top = 1;

    cStructure.left=10;

    cStructure.right=20;

    cStructure.bottom=10;

 

    lpStructure = cStructure;

 

    printf(“\nLeft = %d; Top = %d; Right = %d; Bottom=%d”, lpStructure->left, lpStructure->top, lpStructure->right, lpStructure->bottom);

    

    return 0;

}

 

In the highlighted area, operator LPStruct()
does all the magic of converting itself when it is assigned to a pointer. In this case I am returning the self pointer (this).

Advertisements