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 2 18569
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 ~~~~~~~
"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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 code but I
really need help.
thanks,
Zenon
|
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 discussions of
new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for
currently. I've searched around for about the last too weeks and have read up on new and overloading it to
some extent but...
|
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 pertaining to
casting class A to class B, the implementation of the
|
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 )
|
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 uses map<and
heavy overloading.
The problem is, the output file differs from input, and for the love of
me I can't figure out why ;p
#include <iostream>
#include <fstream>
#include <sstream>
| |
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
{
public:
operator string(); // allow this class to be typecast into a string
operator char*(); // allow this class to be typecast into a char*
|
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, obj2 ;
|
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 & operator>(std::istream & in, const Complex & a);
// the methods correspond to the friend
std::istream & operator>(std::istream & in, const Complex & a)
{
std::cout << "real: ";
|
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,
operator =, operator, operator(), and operator-must be nonstatic
member function; this ensures that their first operands will be
lvalues". I know that these operators must be nonstatic member
functions, but why this ensure their first operands will...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |