473,881 Members | 1,670 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why define operator == global and not as a class member?

Hello everybody,

Stroustrup says he prefer's to declare operators, which do not do anything
on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?

Thank you, Peter
Jul 22 '05 #1
5 1895
"Peter Meier" <pe*********@ ar-solutions.de> wrote...
Stroustrup says he prefer's to declare operators, which do not do anything
on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?


Advantage is the possibility to use the implicit conversions that
are often defined by the class itself.

Example 1 (member):

class A
{
int i;
public:
A(int ii) : i(ii) {}
bool operator ==(A const& a) const { return i == a.i; }
};

int main()
{
A a1(42), a2(73);
a1 == a2; // works fine
a1 == 12; // works fine, '12' is converted into a temporary A
666 == a2; // ERROR doesn't work, '666' cannot be converted
}

Example 2 (non-member)

class A
{
int i;
public:
A(int ii) : i(ii) {}
int get() const { return i; }
};

bool operator ==(A const& a1, A const& a2)
{
return a1.get() == a2.get();
}

int main()
{
A a1(42), a2(73);
a1 == a2; // works fine
a1 == 12; // works fine, '12' is converted into a temporary A
666 == a2; // works fine, '666' is converted into a temporary A
}

I am surprised that you didn't find Dr.Stroustrup's explanation as to
why non-members are better.

Victor
Jul 22 '05 #2
Peter Meier wrote:
Hello everybody,

Stroustrup says he prefer's to declare operators, which do not do anything
on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?

Thank you, Peter


It makes the syntax similar for built-in and user-defined types.
Similar syntax makes generic programming simpler.
Also, IMO, it's a good idea to limit the number of class methods as much
as possible, so that it's relatively easy to monitor accesses to the
class data.
Jul 22 '05 #3
"Jeff Schwab" <je******@comca st.net> wrote...
Peter Meier wrote:
Hello everybody,

Stroustrup says he prefer's to declare operators, which do not do anything on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?

Thank you, Peter
It makes the syntax similar for built-in and user-defined types.


Huh?

struct A {
bool operator==(A const&) const { return false; }
};

int main() {
A a1, a2;
a1 == a2; // Different ???
}
Similar syntax makes generic programming simpler.
So, what's the advantage of making it non-member?
Also, IMO, it's a good idea to limit the number of class methods as much
as possible, so that it's relatively easy to monitor accesses to the
class data.


Who says that the members have to access class data directly? If you
are so inclined to monitor the access, use accessors and monitor.

Victor
Jul 22 '05 #4
Victor Bazarov wrote:
"Jeff Schwab" <je******@comca st.net> wrote...
Peter Meier wrote:
Hello everybody,

Stroustrup says he prefer's to declare operators, which do not do
anything
on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?

Thank you, Peter


It makes the syntax similar for built-in and user-defined types.

Huh?

struct A {
bool operator==(A const&) const { return false; }
};

int main() {
A a1, a2;
a1 == a2; // Different ???
}


You're right, for operators the syntax is identical.
Also, IMO, it's a good idea to limit the number of class methods as much
as possible, so that it's relatively easy to monitor accesses to the
class data.


Who says that the members have to access class data directly? If you
are so inclined to monitor the access, use accessors and monitor.


....or just don't make things members if they don't need to be.

Jul 22 '05 #5

"Jeff Schwab" <je******@comca st.net> wrote in message
news:k5******** ************@co mcast.com...
Victor Bazarov wrote:
"Jeff Schwab" <je******@comca st.net> wrote...
Peter Meier wrote:

Hello everybody,

Stroustrup says he prefer's to declare operators, which do not do
anything
on the class itself global. Does anybody know the reason for that?
Any advantages/disadvantages?

Thank you, Peter

It makes the syntax similar for built-in and user-defined types.

Huh?

struct A {
bool operator==(A const&) const { return false; }
};

int main() {
A a1, a2;
a1 == a2; // Different ???
}


You're right, for operators the syntax is identical.


Perhaps you were thinking of the symmetry issue when you want to compare
class to a
builtin- type:
You can write an operator for A() == 42 either as a member or non-member but
42 == A() can only be done with
a non-member.
The usual method is:
struct A
{
A(int x); // conversion from int
int compare(const A&) const; // return positive neagtive or 0 for >,==,<
};
inline bool operator==(cons t A& a,const A& b) { return a.compare(b) == 0; }

This handles both the cases above by converting the int to an A;

The use of the compare member means that all comparisions are done in one
method and the usual operators
can be trivivially defined as inline non-members that do not need friend
access e.g.

inline bool operator<=(cons t A& a,const A& b) { return a.compare(b) <= 0; }
etc.
Also, IMO, it's a good idea to limit the number of class methods as much
as possible, so that it's relatively easy to monitor accesses to the
class data.


Who says that the members have to access class data directly? If you
are so inclined to monitor the access, use accessors and monitor.


...or just don't make things members if they don't need to be.

Jul 22 '05 #6

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

Similar topics

2
5890
by: victor75040 | last post by:
Before you all start flaming me, I am not a student and this is not for any homework. Just someone learing c++ on their own. I am now up to the chapter in my book that describes operator overloading. I just cannot find any explanation that clearly point out what the parts of the statement refer to. For example the book says: comp operator+(comp b)
10
2319
by: Piotr Wyderski | last post by:
Hello, is it possible to reuse a friend operator which is defined inside a class? I'd like to obtain the following behaviour: class integer { integer operator +(signed long int v) const {
5
3619
by: eiji | last post by:
Hi folks, I hope this is not "off topic"! :-) Consider the next code: /* Declarations of types that could become platform-dependent */ #define MyChar char #define MyInt int
5
3635
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), , ->, =. I wonder why there is such a restriction. Some tutorials say that 'new' and 'delete' can only be overloaded with static member functions, others say that all overloading function should be non-static. Then what is the fact, and why? ...
7
2809
by: Eric Lilja | last post by:
>From a book, I know the following is true for the comparison operators: An overloaded operator that is a class member is only considered when the operator is used with a *left* operand that is an object of that class. And is that also the reason why if you use class member functions for operators << and >you have to write: someclass << cout; someclass >cin; ?
3
3291
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 ;
8
2122
by: pauldepstein | last post by:
The following code was written by a colleague -- to preserve confidentiality, the name of the class is changed: HisClass operator+ (const HisClass & h1, const HisClass & h2) { // some code here} HisClass HisClass::operator+ (const HisClass& h2) {// more code here}
3
3820
by: news.aioe.org | last post by:
Is it possible to overload increment(++) and decrement(--) postfix and prefix operators for primitive datatypes such as int, char, short, etc. in global scope (vs as a class member function where this is possibe)? If there is a site that lists all operators that can't be overloaded (such as the member access dot operator), please post it. thanks
7
3056
by: Bill Davy | last post by:
I want to be able to write (const char*)v where v is an item of type Class::ToolTypeT where ToolTypeT is an enumeration and I've tried everything that looks sensible. There's an ugly solution, but surely this is possible? I could define an operator<< but for various reasons, I really want to convert to a 'const char*' (to embed into a string which becomes part of a window's caption, etc).
0
9776
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
11100
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
10718
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
10401
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
7110
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
5781
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
5977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4196
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3225
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.