0

So I have in stockType.h

#include <iostream>
class stockType {
public:
    //...
    static friend std::ostream& operator<<(std::ostream& out, const stockType& stock);
    static friend std::istream& operator>>(std::istream& in, stockType& stock);
private:
    //...
}

and in stockType.cpp

std::ostream& operator<<(std::ostream& out, const stockType& stock) {
    //...
}

std::istream& operator>>(std::istream& in, stockType& stock) {
    //...
}

I'm having no issues with operator<< but the compiler gives me a fatal error "static function 'std::istream &operator >>(std::istream &,stockType &)' declared but not defined" and it says it occurs on main.cpp line 32 but there's only 31 lines in main.cpp.

  • 1
    You promised to make them static class functions, but you defined them as free functions. FYI friend is odd for class members. Remove `static`. – 273K Nov 27 '21 at 17:42
  • Hidden friends is a good way to do operator overloading. Otherwise it slows down the overload resolution stage. But yeah, no need for `static` here - it's already not a member function because it's a friend so `static` apparently refers to visibility here. – unddoch Nov 27 '21 at 17:46

1 Answers1

1

Marking a free function (friend functions aren't methods in a class) as static indicates that it will be defined in the current translation unit. Putting a static function in a header means that all translation units including that header must have their own definition of that function. You should remove static from your declarations (clang and gcc actually reject your code as invalid).

Note that this is different to static member functions which indicate that the method is available in the class rather than in instances. This is one of the many confusing places that c++ uses the same keyword to mean different things in different contexts.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • So since stream insertion and extraction operators aren't member functions, basically I can either declare them static outside the class or friend inside the class, but not both? I had an issue a previous time where I needed to make the overload static to fix it, but I think it was declared outside the class and not a friend. – Justin Iaconis Nov 27 '21 at 18:57
  • 1
    @JustinIaconis stream operators (and operators in general) should not be static, they should be non-static members or free functions, see https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/4421719#4421719. If functions are defined in headers they should be marked `inline` not `static` – Alan Birtles Nov 27 '21 at 19:01