473,701 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloaded typecast operators and copy constructors

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
overloaded typecast operator does something like this:

A::operator B(...)
{
B localCopy(...);
// perhaps some attributes of the "this" object
// are passed to the constructor

return localCopy;
}

Is this correct? Aren't we returning a local copy of
B?
(2) It appears that the following syntaxes are
equivalent:
[Here b is an instance of Class Y and Class Y has an
overloaded typecast operator for Class X]
(a) X c = (X)b; // Typecast style
(b) X c = X(b); // Function call style

Is this correct?
(3) I am surprised that the typecasting to self type is
allowed. If we have a class that supports both a copy
constructor with one argument and an overloaded
typecast operator to its own type (for whatever
reason), it appears that they will have identical
calling syntaxes.

Is this correct? If this is correct, how does the
compiler remove the ambiguity.

I have a small coding sample that illustrates my
doubts.
/////////////////////////////////////////////////////////////
#include <string.h>
#include <iostream.h>

class First
{
int value;
public:
First(int i = 0)
{
value = i;
}

operator int() // typecast to integer
{
return value;
}
};
class Second
{
int data;
char label[100];

public:
Second(int i = 0, char* str = "???")
{
data = i;
strcpy(label, str);
}

Second(const Second& obj) // Copy constructor
{
cout << "Copy constructor called\n";
data = obj.data;
strcpy(label, obj.label);
}

operator char*() // typecast to char*
{
return label;
}

operator First() // typecast to First
{
First f(data);
return f;
}

operator Second() // typecast to Self-type
{
cout << "Typecast operator to self called\n";
Second s(data, label);
return s;
}
};
int
main()
{
First first_a(56);

cout << "It is " << (int)first_a << endl;

Second second_b(98, "Howdy Doody");

First first_c = (First)second_b ; // typecast style conversion
First first_d = First(second_b) ; // function call style conversion

cout << "ONE: It is " << (int)first_c
<< " and " << (char *)second_b << endl;
cout << "TWO: It is " << (int)first_d
<< " and " << (char *)second_b << endl;

Second second_e(second _b);
// What got called ---- the overloaded typecast
// self-type or the copy constructor?

return 0;
}

Jul 23 '05 #1
1 2222
<ma**********@l ycos.com> wrote...
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
overloaded typecast operator does something like this:

A::operator B(...)
{
B localCopy(...);
// perhaps some attributes of the "this" object
// are passed to the constructor

return localCopy;
}

Is this correct? Aren't we returning a local copy of
B?
It is correct. We're returning a copy of 'localCopy'.
(2) It appears that the following syntaxes are
equivalent:
[Here b is an instance of Class Y and Class Y has an
overloaded typecast operator for Class X]
(a) X c = (X)b; // Typecast style
(b) X c = X(b); // Function call style

Is this correct?
Depends on what 'X' is like. If it has a constructor that
accepts 'Y', then no, it's not correct.
(3) I am surprised that the typecasting to self type is
allowed.
You mean

struct A {
operator A();
};

?
If we have a class that supports both a copy
constructor with one argument and an overloaded
typecast operator to its own type (for whatever
reason), it appears that they will have identical
calling syntaxes.
It does, doesn't it?
Is this correct? If this is correct, how does the
compiler remove the ambiguity.
The conversion to the same object type is never used
directly. It can only be reached through a virtual
function call. See 12.3.2/1.

I have a small coding sample that illustrates my
doubts.
/////////////////////////////////////////////////////////////
#include <string.h>
#include <iostream.h>
#include <iostream>
using std::cout;
using std::endl;

class First
{
int value;
public:
First(int i = 0)
{
value = i;
}

operator int() // typecast to integer
{
return value;
}
};
class Second
{
int data;
char label[100];

public:
Second(int i = 0, char* str = "???")
Second(int i = 0, char const* str = "???")
{
data = i;
strcpy(label, str);
strncpy(label, str, 99);
label[99] = 0;
}

Second(const Second& obj) // Copy constructor
{
cout << "Copy constructor called\n";
data = obj.data;
strcpy(label, obj.label);
}

operator char*() // typecast to char*
{
return label;
}

operator First() // typecast to First
{
First f(data);
return f;
}

operator Second() // typecast to Self-type
{
cout << "Typecast operator to self called\n";
Second s(data, label);
return s;
}
};
int
main()
{
First first_a(56);

cout << "It is " << (int)first_a << endl;

Second second_b(98, "Howdy Doody");

First first_c = (First)second_b ; // typecast style conversion
First first_d = First(second_b) ; // function call style conversion

cout << "ONE: It is " << (int)first_c
<< " and " << (char *)second_b << endl;
cout << "TWO: It is " << (int)first_d
<< " and " << (char *)second_b << endl;

Second second_e(second _b);
// What got called ---- the overloaded typecast
// self-type or the copy constructor?
The copy constructor.

return 0;
}

Jul 23 '05 #2

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

Similar topics

8
17873
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. Why can't the = (assignment) operator be overloaded as a friend function ? I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it said the following :
5
6883
by: Andy Jarrell | last post by:
I'm trying to inherit from a specific class that has an overloaded operator. The problem I'm getting is that certain overloaded operators don't seem to come with the inheritance. For example: // TestA.h --------------------------------------- #include <iostream> enum Aval { FIRST_VALUE,
3
1704
by: N4M | last post by:
Dear, I have problems with overloaded operators ++() and --(). MSVC++ 6.0 compiler gives errors, one is shown as below: " c:\data\c++\mygraphs\graph.h(182) : error C2555: 'CGraphNodeIter::++' : overriding virtual function differs from 'CGraphNodeIterI::++' only by return type or calling convention c:\data\c++\mygraphs\graph.h(141) : see declaration of 'CGraphNodeIterI' "
4
1820
by: August1 | last post by:
I've written an interface and implementation file along with a client source file that allows the use of an overloaded subtraction operator. However, when using the program, I'm running into a memory problem that I'm not readily seeing that lies within the overloaded operator - I think pertaining to the temporary class object that is created and used to return a value of the operands and the pointer variable of the class. Could someone...
14
3654
by: ambar.shome | last post by:
Hi, As you know there are few operators in C++ which cant be overloaded. They are: .., .*, ::, ?: , new , delete , sizeof , typeid , static_casr , dynamic_cast , const_cast , reinterpret_cast . Theremust be some reason for this restriction for each of the
5
2292
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason my C++.NET 2.0 textbook does not have one. I tried to build one using the format as taught in my regular C++ book, but I keep getting compiler errors. Some errors claim (contrary to my book) that you cannot use a static function, that you must...
3
4085
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*
3
1744
by: iluvatar | last post by:
Hi all. I have written a 3d-vector class (for 3-dimensional space) and I have overloaded the arihtmetic operators like +, +=, * and so on. Also, the constructor works with doubles and has default arguments. In my class, the operator = works for another vector (just copying the elements), and for a double: in this cases each element of the vector will be equal to the double. Example:
5
2277
by: sam_cit | last post by:
Hi Everyone, I was just wondering, about the overloaded assignment operator for user defined objects. It is used to make sure that the following works properly, obj1 = obj; so the overloaded operator function performs the necessary copy of obj's member in to obj1. Can't the same be done using copy
0
8736
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, 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...
0
8649
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9229
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9083
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 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...
0
8934
tracyyun
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...
0
5904
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4410
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...
1
3102
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2035
bsmnconsultancy
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...

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.