Jump to content
  • Advertisement
Sign in to follow this  

constructing an object and passing it by reference

This topic is 4520 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can someone help me with the following?
class foo
{
  public:
    foo(int i) { in = i; }
  int in;

  inline bool operator< (foo &ref)
  {
    return (in < ref.in);
  }
};

void func()
{
  foo a(10);

  if (a < foo(5)) // this won't work cuz operator< expects a reference
  // is there a way around this?
  ...

}

Share this post


Link to post
Share on other sites
Advertisement
Just a note: might want that function to take a const Foo & and not just a Foo &. Moreover the function itself should be const, as it isn't modifying the lhs of the equation.

Share this post


Link to post
Share on other sites
Oh! And there is a choice you should make. Do you want implicit conversion from an int to a Foo? If so, you don't need to a < Foo( 5 ) and can just a < 5.

If you don't want implicit conversion (which I definatly suggest) then you should make that constructor explicit.

Share this post


Link to post
Share on other sites
Quote:
Original post by bradbobak

if (a < foo(5)) // this won't work cuz operator< expects a reference
// is there a way around this?

Yes. The parameter must be a const reference for passing temporary objects to work. You should always pass arguments as either a const reference or a value, if you aren't going to modify the argument. Also, the function should itself be marked const to indicate that *this is not going to be modified.

bool operator < (const foo &ref) const

Moreover, the operator < should probably be a free function, that is:

// outside a class
bool operator < (const foo &left, const foo &right);


If you need to access foo's private members, declare the function as a friend; in this case, you can also define it right there in the friend declaration, like this:

class foo
{
private:
int in;
public:
friend bool operator < (const foo &left, const foo &right)
{
return left.in < right.in;
}
};

You don't need to use the inline keyword when defining a function inside a class declaration.

Also, you should make a habit of using initializer lists in constructors:

foo(int i) : in(i) { }


EDIT: ProgramMax: Guilty as charged :/

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!