С++ operator class
12:33 02 Oct 2026

Here is the question: how can I make the `Counter` class's `operator+` function access the private `int value` variable? After all, that requires making the function a "friend"—meaning it must be declared before the class definition and then specified inside the class—but the compiler won't know the function's type at that point.

#include 

Counter operator + (const Counter& c1, const Counter& c2);

class Counter
{
    friend Counter operator + (const Counter& c1, const Counter& c2);
public:
    Counter(int val){
        value = val;
    }
    void print(){
        std::cout << value << std::endl;
    }
private:
    int value;
};

Counter operator + (const Counter& c1, const Counter& c2)
{
    return Counter{c1.value + c2.value};
}

int main(){
    Counter c1 {10};
    Counter c2 {15};
    Counter c3 = c1 + c2;
    c3.print();
}

c++