Search code examples
c++classconstantsfriend

Friend methods as Constant


Why can't I declare a friend function as const?

//Types.h
#pragma once
#include <string>
#include <ostream>

class Player
{
public:
    //constructors
    Player();
    Player(const std::string&, unsigned short);

    //operator overload
    friend std::ostream& operator<<(std::ostream&, const Player&);
//                  (I can't declare it as const)

    //getter
    const std::string& get_id() const;

private:
    std::string id;
    unsigned short lvl;
};
//Types.cpp
#include "Types.h"
#include <iostream>
#include <iomanip>

/*other definitions*/

std::ostream& operator<<(std::ostream& out, const Player& print)
{
    out << "Player: " << std::setw(6) << print.id << " | " << "Level: " << print.lvl;
    return out;
}

I mean, if I want to call operator<< on a constant variable or in a constant function, I will get an error because operator<< is not constant, even if it doesn't change anithing inside the class.


Solution

  • But operator<< is not a member - it's a free function. So there's no base object that it's not modifying.

    int myFunc() const {
        return 3;
    }
    

    Also gets an error from the compiler:

    error: non-member function 'int myFunc()' cannot have cv-qualifier
    

    Your version of operator<< is also quite strange as it doesn't output anything to the stream it's supposed to, preferring instead to output things to std::cout!

    I think you should reconsider what you hope to achieve, as you're trying to do something non-standard. If you just want a method that writes the contents of your class to std::cout, then just do that, rather than overloading the operator.

    Note that if you had some other iostream, you'd be surprised that nothing goes into it!

    std::ofstream myFile("my_path");
    myFile << Player;