472,371 Members | 1,668 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,371 software developers and data experts.

Overloading unary minus for use in function calls

I would like to overload the unary minus operator so that I can negate
an instance of a class and pass that instance to a function without
creating an explicit temporary variable. Here is an example:

#include <iostream>
using namespace std;

class Object
{
public:
int number;
Object(int value);
const Object operator- ();
//friend const Object operator- (const Object& o);

};

Object::Object(int value) :
number (value)
{}

const Object Object::operator- ()
{
cout << "using class minus" << endl;
number = -number;
return *this;
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/

void useAnObject(Object& o)
{
cout << "using object with number: " << o.number << endl;
}

int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}

When I compile this, I get the following errors (gcc 4.0.1):
c++ unaryminus.cpp -o unaryminus
unaryminus.cpp: In function 'int main(int, char**)':
unaryminus.cpp:39: error: invalid initialization of non-const reference
of type 'Object&' from a temporary of type 'const Object'
unaryminus.cpp:31: error: in passing argument 1 of 'void
useAnObject(Object&)'

I have tried various combinations of returning void, returning const
Object, returning non-const Object, returning reference to Object, etc,
but i get similar errors. Is there a way to do this?

-Matthew

Dec 20 '06 #1
6 2488
IR
Matthew Cook wrote:
I would like to overload the unary minus operator so that I can
negate an instance of a class and pass that instance to a function
without creating an explicit temporary variable. Here is an
example:

#include <iostream>
using namespace std;

class Object
{
public:
int number;
Object(int value);
const Object operator- ();
operator -() should not modify the object, so it should be declared
const.
Also, are you sure you are willing to return a const Object?

I'd rather declare it:

Object operator -() const;

//friend const Object operator- (const Object& o);

};

Object::Object(int value) :
number (value)
{}

const Object Object::operator- ()
{
cout << "using class minus" << endl;
number = -number;
return *this;
}
Object Object::operator -() const
{
cout << "Object::operator -()" << endl;
return Object(-number);
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/

void useAnObject(Object& o)
{
cout << "using object with number: " << o.number << endl;
}

int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
It works now :p
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}

When I compile this, I get the following errors (gcc 4.0.1):
c++ unaryminus.cpp -o unaryminus
unaryminus.cpp: In function 'int main(int, char**)':
unaryminus.cpp:39: error: invalid initialization of non-const
reference of type 'Object&' from a temporary of type 'const
Object' unaryminus.cpp:31: error: in passing argument 1 of 'void
useAnObject(Object&)'
The compiler said it: your operator -() returned a const Object,
while useAnObject expected an Object&. How could the compiler cast
the const away?
Cheers,
--
IR
Dec 20 '06 #2
Matthew Cook wrote:
>
void useAnObject(Object& o)
{
cout << "using object with number: " << o.number << endl;
}

int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}

When I compile this, I get the following errors (gcc 4.0.1):
c++ unaryminus.cpp -o unaryminus
unaryminus.cpp: In function 'int main(int, char**)':
unaryminus.cpp:39: error: invalid initialization of non-const reference
of type 'Object&' from a temporary of type 'const Object'
unaryminus.cpp:31: error: in passing argument 1 of 'void
useAnObject(Object&)'

I have tried various combinations of returning void, returning const
Object, returning non-const Object, returning reference to Object, etc,
but i get similar errors. Is there a way to do this?
The compiler is telling you that you can't bind a temporary object to a
non const reference. You are also attempting to assign a cost reference
to a reference.

void useAnObject( const Object& o)

will see you right.

--
Ian Collins.
Dec 20 '06 #3
Matthew Cook wrote:
I would like to overload the unary minus operator so that I can negate
an instance of a class and pass that instance to a function without
creating an explicit temporary variable. Here is an example:

#include <iostream>
using namespace std;

class Object
{
public:
int number;
Object(int value);
const Object operator- ();
Why are you returning a "const Object" ? You may as well return an Object.

I also suspect that "- OBJ" should not change OBJ. So operator- should
be a const function.

i.e.
Object operator- () const;
//friend const Object operator- (const Object& o);

};

Object::Object(int value) :
number (value)
{}

const Object Object::operator- ()
Object operator- () const
{
cout << "using class minus" << endl;
number = -number;
Can't be messing with number.
return *this;
Return a different Object.

return Object( -number );
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/

void useAnObject(Object& o)
If you want to accept references to temporaries as arguments, you must
make them "const" temporaries.

void useAnObject(const Object& o)

{
cout << "using object with number: " << o.number << endl;
}

int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}

When I compile this, I get the following errors (gcc 4.0.1):
c++ unaryminus.cpp -o unaryminus
unaryminus.cpp: In function 'int main(int, char**)':
unaryminus.cpp:39: error: invalid initialization of non-const reference
of type 'Object&' from a temporary of type 'const Object'
unaryminus.cpp:31: error: in passing argument 1 of 'void
useAnObject(Object&)'

I have tried various combinations of returning void, returning const
Object, returning non-const Object, returning reference to Object, etc,
but i get similar errors. Is there a way to do this?
#include <iostream>
using namespace std;

class Object
{
public:
int number;
Object(int value);
Object operator- () const;
//friend const Object operator- (const Object& o);

};

Object::Object(int value) :
number (value)
{}

Object Object::operator- () const
{
cout << "using class minus" << endl;
return Object( -number );
}
/*
const Object operator- (const Object& o)
{
cout << "using friend minus" << endl;
return Object(-o.number);
}*/

void useAnObject(const Object& o)
{
cout << "using object with number: " << o.number << endl;
}

int main(int argc, char* argv[])
{
Object a(4);
useAnObject(-a); // does not work but would like it to
//Object b = -a; // works, but I don't like it
//useAnObject(b);
}

>
-Matthew
Dec 20 '06 #4
IR
Ian Collins wrote:
The compiler is telling you that you can't bind a temporary object
to a non const reference.
Damn, I missed this one... and VC8 didn't even blink on it :-/
Cheers,
--
IR
Dec 20 '06 #5
Thanks to everyone for the quick reply.

I was returning const Objects on the advice of Effective C++'s Item 3
(top of pg 13, possibly over-liberally applied in this case).

I guess what I was really trying for was a function to negate the
object in place rather than making a copy. However the more I look at
things, the less this seems to fit with the expected behavior of
overloading this operator. I think an explicit negate function might
be more appropriate.

For those who may find their way across this post in the future, IR's
raises a good point in the prev post. This seem to only work when the
temporary object created is passed as constant regardless of the return
type of the operator-. It seems to be the case that implicit temporary
variables like this are always const (perhaps someone can quote chapter
and verse from the standard.) However, I was sure I'd done this on
VC++ in the past. It appears the case may have changed. Google
provides this tidbit from microsoft:

http://msdn2.microsoft.com/en-US/lib...dc(vs.80).aspx

Many Thanks,
-Matthew

Dec 20 '06 #6
IR
Matthew Cook wrote:
For those who may find their way across this post in the future,
IR's raises a good point in the prev post.
I did not raise that issue. Ian Collins and Gianni Mariani did. I
was only a victim of both my compiler and my thoughtlessness. ;-)
This seem to only work
when the temporary object created is passed as constant regardless
of the return type of the operator-. It seems to be the case that
implicit temporary variables like this are always const (perhaps
someone can quote chapter and verse from the standard.) However,
I was sure I'd done this on VC++ in the past. It appears the case
may have changed. Google provides this tidbit from microsoft:

http://msdn2.microsoft.com/en-US/lib...dc(vs.80).aspx
Although I can't quote the relevant paragraph from the standard, the
link you provided is right (in theory, not in practice).

VC8 didn't generate an error (as it should, to my understanding)
either with the code I posted earlier, nor with the following code:

class C {};
void f(C & c) {}

int main()
{
f(C());
}

(of course, Comeau correctly identifies the error)
FWIW, I figured out that VC8 generates this error only when M$
language "extensions" are disabled. Otherwise, it only issues a
warning when at maximum warning level (4).

What got me wrong is that I always keep those extensions enabled
(because when disabled, Windows headers simply don't compile), and
that my test project wasn't at warning level 4 contrary to my habit.

I guess this will teach me to *always* double-check that my compiler
options are the strictest possible... :-)
Cheers,
--
IR
Dec 20 '06 #7

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

Similar topics

17
by: Terje Slettebų | last post by:
To round off my trilogy of "why"'s about PHP... :) If this subject have been discussed before, I'd appreciate a pointer to it. I again haven't found it in a search of the PHP groups. The PHP...
3
by: Carlos Ribeiro | last post by:
I was checking the Prolog recipe in the Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303057 It's a clever implementation that explores some aspects of Python that I wasn't...
6
by: Andrew Ward | last post by:
Hi All, I tried to compile the following line: pair<long, ulong> cr3(make_pair(-2147483648L, 2147483647)); but get this error: unary minus applied to unsigned type, result still unsigned. ...
2
by: Javier Estrada | last post by:
1. For types smaller than int, when I compile: class MyClass { static void Main(string args) { x = 10; y = -x; }
13
by: Marc | last post by:
Hi, I've been lurking on clc for a few months now, and want to start by thanking the regulars here for opening my eyes to a whole new dimension of "knowing c". Considering I had never even...
5
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: (), ,...
28
by: dspfun | last post by:
I'm trying to get a good understanding of how unary operators work and have some questions about the following test snippets. int *p; ~!&*++p--; It doesn't compile, why? The problem seems to be...
19
by: Jess | last post by:
Hello, After seeing some examples about operator overloading, I'm still a bit confused about the general syntax. The following is what I think, not sure whether it's correct. 1. For a unary...
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,...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

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.