473,387 Members | 1,516 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,387 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 18539
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.