0

What's wrong with my static topStock method? It takes in a reference to Stock s and Stock t. Shouldn't it return a copy of s or t?

error: expected primary-expression before '.' token|

#include <iostream>

using namespace std;

class Stock {

public:

    Stock() : x(0){ }
    Stock(int val) : x(val){}

    void display() const;

    static Stock topStock(const Stock& s, const Stock& t) {
     if (s.x > t.x)
        return s;
    else
        return t;
    }

    int x;
};

void Stock::display() const
{

    std::cout << this->x;

}


int main()
{
    Stock s(9);
    Stock y(8);
    Stock z = Stock.topStock(s, y);
    return 0;
}
runners3431
  • 1,425
  • 1
  • 13
  • 30
  • 1
    @WhozCraig Don't return the reference if it may be a reference to a temporary that will be destroyed soon after the function returns. –  Sep 18 '13 at 20:02
  • @hvd Are you saying even if s and y are temporaries passed as const-ref the lifetime of the return value, also a const-ref, will *not* be extended?? – WhozCraig Sep 18 '13 at 20:04
  • @hvd Are you saying even if s and y are temporaries passed as const-ref the lifetime of the return value, also a const-ref, will *not* be extended?? I believe you're correct now that I think about it, since the standard only defined *local* temporaries having extended lifetime; not parameters passed in. Is that accurate? – WhozCraig Sep 18 '13 at 20:08
  • @WhozCraig Yes, hiding the intended lifetime extension through a function call is one of the exceptions where it is not required to work (in fact, where it is required not to work, I think). It's not realistic to expect a compiler to be able to compile `const S &s = f(S());` and know when to call the temporary's destructor, if that may depend on whether `f` returns that temporary. –  Sep 18 '13 at 20:08
  • Yeah, now that you bring it up, [this question](http://stackoverflow.com/questions/2784262/does-a-const-reference-prolong-the-life-of-a-temporary) covers that very topic extensively. Thanks for keeping me honest =P – WhozCraig Sep 18 '13 at 20:08

1 Answers1

6

Change

Stock.topStock(s, y);

to

Stock::topStock(s, y);

because it is a static member function.

David G
  • 94,763
  • 41
  • 167
  • 253