Click here to Skip to main content
15,913,118 members
Please Sign up or sign in to vote.
1.00/5 (5 votes)
See more:
What is the use of conversion operator and how to declare in C++.

-RCR
http://ccppcoding.blogspot.in/[^]
Posted

1 solution

Conversion operators are can be used when where you want to use your object in place of some another datatype ....

For example ....

If we have a class called TestClass like

C++
class TestClass
{
  bool m_bTestMember;
public:
TestClass()
{
   m_bTestMember= false;
}
SetTestMember( bool i_bSet )
{
m_bTestMember=i_bSet;
}

} 




int main()
{
  TestClass test;
  if (test)  //You cannot use this object here, as IF expects some boolean(or integer) stuff
  {
    printf("Hurray");
  }
  else
  {
    printf("BadLuck");
  }

}

Hence to able to use test in if condition you will need to add conversion operator in your class...like follwoing one

C++
class TestClass
{
  bool m_bTestMember;
public:
TestClass()
{
   m_bTestMember= false;
}
SetTestMember( bool i_bSet )
{
m_bTestMember=i_bSet;
}

//Conversion opoerator for bool
operator bool()
{
  return m_bTestMember;
}

}


Now you can use object of this class in IF condition.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900