You are here:

C++/Overload typecast operator in cpp

Advertisement


Question
class base
{
public:
int x;
};

int main()
{
int p;
base b;
b.x=5;
p=(int)b;//i want this to execute fine.what should be my overload        function
return 0;
}

Answer
You need a conversion operator member function - and like operator function overloads - such as those for assignment ( = ), equality ( ==, != ), etc. - we use the operator keyword. In this case the type we wish to convert to is the operator name. No parameters are required, nor is a return type as the compiler is smart enough to deduce that if we wish to convert our type to some type T then a value of type T is what is supposed to be returned!

So in your case you require an operator int() and it will, I assume, return the value of x as a copy. As its use does not and cannot cause changes to the converted from base object it can be qualified const:

   class base
   {
   public:
       int x;

       operator int() const
       {
         return x;
       }
   };

This will allow implicit conversions without an explicit type cast:

   int main()
   {
       int p;
       base b;
       b.x = 5;
       p = b;        // NOTE: No type cast required
       return 0;
   }

In C++11 we can mark conversion operators as explicit:

   class base
   {
   public:
       int x;

       explicit operator int() const
       {
         return x;
       }
   };

In which case an explicit type cast is required to make use of the conversion operator:

   int main()
   {
       int p;
       base b;
       b.x = 5;
       p = static_cast<int>(b);  // NOTE: Explicit type cast required to use explicit conversion
       return 0;
   }

However, compilers are still catching up with regard to C++11 features so you will have to check to see if your compiler version supports explicit conversion operators.

Note my use of the narrower in scope C++ static_cast<>() than the C-style cast that will make a conversion if it possibly can even if the result is likely to be problematic - the C-style cast is sometimes described as a 'sledgehammer cast' maybe because it is often a sledgehammer to crack a nut or maybe because it smashes one type into another! C-style casts are also harder to locate in code - especially automatically with say a find operation in an editor as they look similar to other constructs such as function parameter lists, parenthesised expressions, parenthesis wrapped expression parts of if, while, case, for etc. In short: try to minimise type casts and prefer the narrower in scope and easier to search for C++ casts to the old C-style cast.

I am not sure if base is so simple just for the sake of exposition. In case it is not I would have thought that making the data member x private and providing a matching explicit single argument constructor (C++98 or later) would have been better form, oh and maybe also add a default constructor that sets x to zero so it always has a known value:

   class base
   {
       int x;

   public:
       base()
       : x(0)
       {}

       explicit base(int x_initial_value)
       : x(x_initial_value)
       {}

       operator int() const
       {
         return x;
       }
   };

And of course it is best to define variables as near to where they are used as possible and to provide them with initial values where ever possible so in main maybe move the declaration and definition of p to the line it is assigned to:

   int main()
   {
       base b(5);
       int p(b);
       return 0;
   }

Note: For these changes I have left out C++11 features such as explicit with operator int and initialisation using curly braces as I do not know how up to date with such features you or your compiler are <grin/>.

Although not required at the moment as base is the only class, if base is really meant to be the base class of a hierarchy of classes intended for (dynamic) polymorphic use (think virtual member functions, abstract base classes, interfaces) it will require a virtual destructor.

Hope this helps.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.