473,246 Members | 1,544 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

Overloading the typecast operator

There's a rather nondescript book called "Using Borland C++" by Lee
and Mark Atkinson (Que Corporation) which presents a rather good
discussion of typecast operator overloading.

I am presenting below a summary of what I have gathered. I would
appreciate if someone could point out to something that is specific to
Borland C++ and is not supported by the ANSI standard. I am also
concerned that some of the information may be outdated since the book
is quite old (1991 edition).

1). Cast operator functions are declued using the following syntax:
operator typename ();
operator typename* ();

2). The target type of the conversion cannot be an enumeration or a
typedef name.

3). You rannot specify a return type.

4). You cannot declare arguments for a cast operator function. It is
assumed that
the function is dealing with *this as input.

5). Cast operator functions are inherited and they can be virtual
functions

6). Only one cast operator function can be implicitly applied to a
class object

7). Cast operator functions cannot be overloaded

8). A cast operator function in a derived class hides a cast operator
function in its base class only if the target type is exactly the
same.

9). The cast operator functions are used in serializing operations.

// ~~~~~~~ Code snippet begin ~~~~~~~
#include <iostream.h>

//////////////////////////////////////////////////////
class A
{
int dat;

public:
A(int num = 0 ) : dat(num) {}

operator int() {return dat;} // castop to int
};
//////////////////////////////////////////////////////
class X
{
int dat;

public:
X(int num = 0) : dat(num){}

operator int() {return dat;} // castop to int

operator A() // castop to class A
{
A temp = dat;
return temp;
}
};
//////////////////////////////////////////////////////
int main()
{
X stuff = 37;
A more = 0;
int hold;

hold = (int)stuff;
cout << hold << endl;

more = stuff; // convert X::stuff to A::more
hold = (int)more; // convert A::more to int
cout << hold << endl;
}
// ~~~~~~~ Code snippet end ~~~~~~~

Regards,
Nimmi
Jul 22 '05 #1
2 18518
Nimmi Srivastav wrote:
There's a rather nondescript book called "Using Borland C++" by Lee
and Mark Atkinson (Que Corporation) which presents a rather good
discussion of typecast operator overloading.

I am presenting below a summary of what I have gathered. I would
appreciate if someone could point out to something that is specific to
Borland C++ and is not supported by the ANSI standard. I am also
concerned that some of the information may be outdated since the book
is quite old (1991 edition).

1). Cast operator functions are declued using the following syntax:
operator typename ();
operator typename* ();
They are actually not "cast operators", but "conversion operators". And
your second operator is just the same as the first, with typename being
a pointer type.
2). The target type of the conversion cannot be an enumeration or a
typedef name.
I don't see any reason for that. Should both work. Especially the
typedef is just an alias for another type. Wherever you can use the
original type, you can use the typedef too.
3). You rannot specify a return type.
Right. The return type is always the same as the "target type" and must
not be specified again.
4). You cannot declare arguments for a cast operator function.
Right. How could you call it with arguments?
It is assumed that the function is dealing with *this as input.
That's the case for any member function.
5). Cast operator functions are inherited and they can be virtual
functions
Yes.
6). Only one cast operator function can be implicitly applied to a
class object
One implicit conversion is done, be it through a conversion constructor
or a conversion oprerator.
7). Cast operator functions cannot be overloaded
Not quite true. You can have const and non-const overloads.
8). A cast operator function in a derived class hides a cast operator
function in its base class only if the target type is exactly the
same.
Yes. If it's not, it's another conversion operator.
9). The cast operator functions are used in serializing operations.
This is just one example where they might be used. I don't see that as
something that is especially connected to conversion operators.

// ~~~~~~~ Code snippet begin ~~~~~~~
#include <iostream.h>
This is an outdated pre-standard header. Use <iostream> instead.
Everything in there (like cout) will be in namespace std then.

//////////////////////////////////////////////////////
class A
{
int dat;

public:
A(int num = 0 ) : dat(num) {}

operator int() {return dat;} // castop to int
};
//////////////////////////////////////////////////////
class X
{
int dat;

public:
X(int num = 0) : dat(num){}

operator int() {return dat;} // castop to int

operator A() // castop to class A
{
A temp = dat;
return temp;
}
Whenever possible, you should use a conversion constructor in the target
class instead of a conversion operator in the source class. So instead
of that operator A() in X, you should add a constructor to A like:

A(const X& rhs)
: dat(rhs)
{}

This will directly construct the A object from the X object instead of
first default-constructing it and then changing it. Another reason is
that you can make conversion constructors explicit.
But for this to work, your operator int() in X has to be const, like:

operator int() const {return dat;}
};
//////////////////////////////////////////////////////
int main()
{
X stuff = 37;
A more = 0;
int hold;

hold = (int)stuff;
You don't need to cast here, the conversion is done implicitly. You
should also avoid C style casts and use the more fine-grained C++
casts.
cout << hold << endl;
You could just directly write this as:

cout << stuff << endl;

The conversion will be done implicitly.
more = stuff; // convert X::stuff to A::more
hold = (int)more; // convert A::more to int
You can skip that cast, too. Done implicitly.
cout << hold << endl;
}
// ~~~~~~~ Code snippet end ~~~~~~~

Jul 22 '05 #2
"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bv*************@news.t-online.com...
Nimmi Srivastav wrote:
2). The target type of the conversion cannot be an enumeration or a typedef name.


I don't see any reason for that. Should both work. Especially the
typedef is just an alias for another type. Wherever you can use the
original type, you can use the typedef too.


True. Also, in some cases, a typedef is absolutely necessary, e.g.
when converting to a pointer to an array:

struct Thing {
typedef int (*array) [9];
operator array(); // okay
operator int (*) [9] (); // syntax error
};

<snip>
4). You cannot declare arguments for a cast operator function.


Right. How could you call it with arguments?


If they had default values. This would actually be very conveinent: it
would allow the use of the enable_if utility with conversion
operators. (CUJ June 2003)

Jonathan
Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Zenon | last post by:
Folks, I am having a terrible time overloading operators. I have tried what I thought was the correct way, I tried the cheating (friend declarations), all to no avail. Sorry for posting tons of...
5
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that...
1
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen...
5
by: luca regini | last post by:
I have this code class M { ..... T operator()( size_t x, size_t y ) const { ... Operator overloading A ....} T& operator()( size_t x, size_t y )
2
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It...
3
by: ryan.gilfether | last post by:
I have a problem that I have been fighting for a while and haven't found a good solution for. Forgive me, but my C++ is really rusty. I have a custom config file class: class ConfigFileValue...
3
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
2
by: Colonel | last post by:
It seems that the problems have something to do with the overloading of istream operator ">>", but I just can't find the exact problem. // the declaration friend std::istream &...
8
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular,...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.