473,769 Members | 2,019 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Virtual operator overloads don't seem to work?

Hi,
I don't quite get what is going on in this code example:

---------------------------
#include <iostream>

using namespace std;

class Base{
public:
virtual void Test(){
cout << "Base" << endl;
}

virtual bool operator==(cons t Base &other){
cout << "Base Comparison" << endl;
return false;
}
};

class Derived : public Base{
public:
void Test(){
cout << "Derived" << endl;
}

bool operator==(cons t Derived &other){
cout << "Derived Comparison" << endl;
return true;
}
};

int main(int argc, char** argv) {
Base a; //Create a base object
a.Test(); //Outputs "Base" as expected
Derived b, c; //Create two derived objects
b.Test(); //Outputs "Derived" as expected
if(b==c) cout << "True" << endl; //Does derived comparison and
returns true as expected.
Base *d=&b, *e=&c; //Create two base pointers to derived objects
d->Test(); //Outputs "Derived" as expected
if(*d==*e) cout << "True" << endl; //Does base comparison and
returns false!?
return 0;
}
----------------------------
The output is:

Base
Derived
Derived Comparison
True
Derived
Base Comparison

Notice, that the line "d->Test()" works correctly, but the comparison
on the next line does not. The compiler (g++ (GCC) 4.2.3 (Ubuntu
4.2.3-2ubuntu7) ) seems to be ignoring the virtual-ness of
Base::operator= = . Is this correct? Have I made a mistake?
Oct 22 '08 #1
1 6712
On Oct 23, 12:09 am, Stuart Brockman <stuartbrock... @gmail.comwrote :
I don't quite get what is going on in this code example:
---------------------------
#include <iostream>
using namespace std;
class Base{
public:
virtual void Test(){
cout << "Base" << endl;
}
virtual bool operator==(cons t Base &other){
cout << "Base Comparison" << endl;
return false;
}
};
class Derived : public Base{
public:
void Test(){
cout << "Derived" << endl;
}
bool operator==(cons t Derived &other){
cout << "Derived Comparison" << endl;
return true;
}
};
int main(int argc, char** argv) {
Base a; //Create a base object
a.Test(); //Outputs "Base" as expected
Derived b, c; //Create two derived objects
b.Test(); //Outputs "Derived" as expected
if(b==c) cout << "True" << endl; //Does derived comparison and
returns true as expected.
Base *d=&b, *e=&c; //Create two base pointers to derived objects
d->Test(); //Outputs "Derived" as expected
if(*d==*e) cout << "True" << endl; //Does base comparison and
returns false!?
return 0;}
----------------------------
The output is:
Base
Derived
Derived Comparison
True
Derived
Base Comparison
Notice, that the line "d->Test()" works correctly, but the
comparison on the next line does not. The compiler (g++ (GCC)
4.2.3 (Ubuntu 4.2.3-2ubuntu7) ) seems to be ignoring the
virtual-ness of Base::operator= = . Is this correct? Have I
made a mistake?
How could it do otherwise? Base::operator= =() has a different
signature than Derived::operat or==(), so the function in the
derived class hides, rather than overloads, the function in the
base class. Moreover, there's no way you could possibly call
Derived::operat or==(), since it requires a Derived const&, and
can't be called with a Base const& (which is basically what you
get when you dereference a Base const*).

In general, binary operators don't work very well with
inheritance; what you'd really need to make them work is double
dispatch. In the special case of == and !=, you can do
something like:

bool
Derived::operat or==( Base const& other ) const
{
Derived const* p
= dynamic_cast< Derived const* >( &other ) ;
return p != NULL && operator==( *p ) ;
}

in addition to your normal Derived::operat or==, at least if you
decide that two different derived types can never compare equal.
If it makes sense for two different derived types to compare
equal, however (say because they both represent the same value,
but in different ways), you'll need to set up a much more
complicated mechanism.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 23 '08 #2

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

Similar topics

0
1129
by: mm | last post by:
the code public static Main() { enum Test { one = 1, two = 2, three = 3
8
17771
by: Floogle | last post by:
how do i create a virtual == operator. I've tried the following but it's incorrect... class Interface { ... public: virtual bool operator==(const Interface& rhs)const=0;
4
1309
by: Harlan Messinger | last post by:
Since operator overloads into static functions in C#, there really doesn't need to be a connection between the types to which the operator is being applied and the type in which the overload is defined, does there? I mean, there's nothing to prevent the following, right? public class A { public static B operator + (C c, D d) { ... } ... }
1
2057
by: illegal.prime | last post by:
I would like to have an array of objects (whose class I define) and then just invoke either: MyClass clonedArray = (MyClass) myArray.Clone(); OR Array.Copy(myArray, clonedArray, myArray.Length); and have an array of cloned objects (i.e. the new array of objects aren't the objects contained in my original array). But instead it seems necessary for me to have to iterate over my entire array and individually clone each element in the...
4
4744
by: manontheedge | last post by:
i'm working on a C++ program that uses operator overloads (which i'm just learning to use), and i have the ostream working fine, but i'm thinking i'm using it wrong somehow because the ofstream doesn't work. Here's some code fragments... class matrix { public: ...... friend ostream& operator << ( ostream& os, matrix& m );
8
2539
by: sun1991 | last post by:
Hi All, I tried the following code, but it did not work as I think: --- using namespace std; namespace { class Fraction { public:
0
1308
jlm699
by: jlm699 | last post by:
Greetings all, I have this server (running on Linux 2.6.17-gentoo-r9) that I've been tinkering with and I attempted to do a multi-threaded model to accept multiple connections, however I found that it was leaving zombie processes and not cleaning up after itself at all. The main thread was doing a waitpid((pid_t)-1, Null, WNOHANG) and keeping track of the number of clients it created/cleaned up. Since that did not work as I had expected I...
14
2343
by: Hunk | last post by:
Hi I ws wondering if there is a way to implement operator+ in case of virtual classes. Here's the problem. I have to have a base string class from which two classes (normal char string and a hash string class ) are derived. The two derived classes are template classes specifying the sizes. The base class is a non-template class so that it can be used generically in the interface classes. the design would look like
3
1212
by: Howard Swope | last post by:
Greetings: C++ CLR .Net 2 I have a ref class that I have created that wraps an unmanaged pointer. It acts like a smart pointer for reference counted objects for a particular library I am working in. I have overloaded the ->, *, assignment, and equality operators. I have created a ! finalizer and call it from my destructor. However, when I do so, the operator overload returns the type of the wrapped pointer.
0
9420
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
10035
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...
1
9984
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9851
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
8863
agi2029
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...
0
6662
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
5293
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...
0
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3949
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

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.