SyntaxPilot
Courses/C++/Lesson 18

C++ · Lesson 18 of 40 · 12 min

Friend functions, static members, this

queued

These are the notes for C++ episode 18. Episode 17's operator<< had to use getters, because a non-member can't see private data. Here you'll fix that with a friend function, build a bank token machine that needs one shared counter (a static data member), ask the class questions without any object (a static member function), and meet the hidden pointer every member function receives: this. You'll use this to fix a silent bug where a parameter hides a member, and to chain calls with return *this. The mini project is a chai stall order counter. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.

The problem: the private wall

Here's last episode's Duration, but with no getters: we don't want the whole program reading hours and minutes. operator<< reads d.h and d.m directly:

#include <iostream>
#include <string>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.h << "h " << d.m << "m";
    return out;
}

int main() {
    Duration trip(4, 135);
    cout << "Trip: " << trip << endl;
    return 0;
}
error: 'int Duration::h' is private within this context

operator<< is a non-member (it has to be, because cout is on the left, episode 17). To C++, a non-member is a stranger like any other code, so private keeps it out.

Two bad options:

Option Problem
Make h and m public The whole program can break the "minutes are 0-59" rule
Write getters just for printing Extra public functions you didn't want, for one use

We want something in between: let this one function in, and nobody else.

The fix: friend

Think of your locked house. Strangers stay out (that's private). But you give a spare key to one trusted neighbour. It's your choice; the neighbour can't just take one. In C++, the class writes friend followed by the function's declaration, inside its own body:

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    friend ostream& operator<<(ostream& out, const Duration& d);
};
#include <iostream>
#include <string>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    friend ostream& operator<<(ostream& out, const Duration& d);
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.h << "h " << d.m << "m";
    return out;
}

int main() {
    Duration trip(4, 135);
    cout << "Trip: " << trip << endl;
    return 0;
}

Output:

Trip: 6h 15m

(Duration(4, 135) was normalised by the constructor: 135 minutes = 2 h 15 min, so 6 h 15 min.)

What a friend is, and isn't

  • A friend is not a member. Its definition has no Duration:: in front, it has no this, and you call it like a normal function (operator<<(cout, trip), or just cout << trip).
  • Only the class can grant friendship. Encapsulation stays in the class's hands: you can see every friend by reading the class.
  • Friendship is not inherited: a friend of Duration is not automatically a friend of a class derived from it (the neighbour's kids get no key).
  • Friendship is not mutual (not two-way): if A declares B a friend, B can see A's private members, but A can't see B's.
  • You can also define the friend right inside the class (as in the mini project below); it's still a non-member.
  • A whole class can be a friend: friend class Bank; lets every member function of Bank see private data. Use friends sparingly: for operators like << and >>, and for tightly-coupled helper classes.

The token machine: why a normal member can't count

A bank branch: each customer presses a button and gets the next token number, 1, 2, 3. The obvious class:

#include <iostream>
#include <string>
using namespace std;

class Token {
    int number;
    int next = 1;
public:
    Token() { number = next; next++; }
    int num() const { return number; }
};

int main() {
    Token a, b, c;
    cout << a.num() << " " << b.num() << " " << c.num() << endl;
    return 0;
}

Output:

1 1 1

Three customers, all token 1. Why? A normal (non-static) data member belongs to each object. Every token got its own next, born at 1. Token a added one to its own copy, which nobody else ever sees.

The bank In C++
The number printed on each slip, different for everyone int number; one per object
The machine's counter, shared by every slip static int next; one per class
Install it once, set to 1 on day one int Token::next = 1; defined outside the class

static data members: one copy for the class

#include <iostream>
#include <string>
using namespace std;

class Token {
    int number;
    static int next;
public:
    Token() { number = next; next++; }
    int num() const { return number; }
};

int main() {
    Token a, b, c;
    cout << a.num() << " " << b.num() << " " << c.num() << endl;
    return 0;
}
undefined reference to `Token::next'

That's not the compiler, it's the linker (the step that joins compiled code into a program). Inside the class, static int next; is only a declaration: "this will exist". Nobody defined it (created the actual variable). Define it exactly once, outside the class:

#include <iostream>
#include <string>
using namespace std;

class Token {
    int number;
    static int next;
public:
    Token() { number = next; next++; }
    int num() const { return number; }
};
int Token::next = 1;

int main() {
    Token a, b, c;
    cout << a.num() << " " << b.num() << " " << c.num() << endl;
    return 0;
}

Output:

1 2 3
  • A static member exists even before the first object is made, and lives until the program ends.
  • sizeof(Token) doesn't include it: it isn't stored inside each object.
  • Since C++17 you can define it inside the class instead: inline static int next = 1;. A static const int or static constexpr int with a value can also be written inside the class.
  • You can reach it as Token::next (if public), or through any object (a.next), which is the very same variable.

static member functions

The manager asks: "how many tokens so far?" That's a question for the machine, not for one slip:

#include <iostream>
#include <string>
using namespace std;

class Token {
    int number;
    static int next;
public:
    Token() { number = next; next++; }
    int num() const { return number; }
    static int issued() { return next - 1; }
};
int Token::next = 1;

int main() {
    Token a, b, c;
    cout << a.num() << " " << b.num() << " " << c.num() << endl;
    cout << "Issued: " << Token::issued() << endl;
    return 0;
}

Output:

1 2 3
Issued: 3

Token::issued() is called on the class; no object is needed. But that means it has no object to work with:

#include <iostream>
#include <string>
using namespace std;

class Token {
    int number;
    static int next;
public:
    Token() { number = next; next++; }
    int num() const { return number; }
    static int issued() { return number; }
};
int Token::next = 1;

int main() {
    Token a, b, c;
    cout << a.num() << " " << b.num() << " " << c.num() << endl;
    cout << "Issued: " << Token::issued() << endl;
    return 0;
}
error: invalid use of member 'Token::number' in static member function

Whose number? A static function can use only static members (and its parameters), because it has no object, and so no this pointer (below).

Normal member function Static member function
Called as a.num() Token::issued() (or a.issued())
Has an object / this yes no
Can use normal members yes no
Can use static members yes yes
Can be virtual / const yes no

The this pointer

A credit card's setLimit takes a parameter named limit, the clearest name, which is also the member's name:

#include <iostream>
#include <string>
using namespace std;

class Card {
    int limit = 0;
public:
    void setLimit(int limit) { limit = limit; }
    int getLimit() const { return limit; }
};

int main() {
    Card card;
    card.setLimit(50000);
    cout << "Limit: " << card.getLimit() << endl;
    return 0;
}

Output:

Limit: 0

No error, and the card is useless. Why? Inside the function, the parameter's name hides (shadows) the member's. So limit = limit copies the parameter onto itself; the member never changes.

Every (non-static) member function secretly receives a pointer to the object it was called on, named this. In card.setLimit(50000), this equals &card. So:

  • this->limit = the object's member
  • limit = the parameter
#include <iostream>
#include <string>
using namespace std;

class Card {
    int limit = 0;
public:
    void setLimit(int limit) { this->limit = limit; }
    int getLimit() const { return limit; }
};

int main() {
    Card card;
    card.setLimit(50000);
    cout << "Limit: " << card.getLimit() << endl;
    return 0;
}

Output:

Limit: 50000

Facts about this:

  • Its type is Card* (in a const member function, const Card*).
  • this->x is the same as (*this).x; inside members you usually write just x, and the compiler adds this-> for you.
  • *this is the object itself.
  • Static member functions have no this, which is exactly why issued() couldn't use number.
  • Another fix is a different parameter name (newLimit) or a constructor initialiser list, where limit(limit) works correctly.

Chaining calls with return *this

A chai stall order: we want to write o.add("chai", 15).add("samosa", 20).add("vada", 25);, like you say it.

#include <iostream>
#include <string>
using namespace std;

class Order {
    string items;
    int total = 0;
public:
    void add(string name, int price) {
        items += name + " ";
        total += price;
    }
    void show() const { cout << items << "= Rs. " << total << endl; }
};

int main() {
    Order o;
    o.add("chai", 15).add("samosa", 20).add("vada", 25);
    o.show();
    return 0;
}
error: invalid use of 'void'

The first add returned void, and you can't call .add on nothing. Return a reference to this same order:

#include <iostream>
#include <string>
using namespace std;

class Order {
    string items;
    int total = 0;
public:
    Order& add(string name, int price) {
        items += name + " ";
        total += price;
        return *this;
    }
    void show() const { cout << items << "= Rs. " << total << endl; }
};

int main() {
    Order o;
    o.add("chai", 15).add("samosa", 20).add("vada", 25);
    o.show();
    return 0;
}

Output:

chai samosa vada = Rs. 60

Order& (a reference, not a copy) matters: returning Order by value would add samosa and vada to temporary copies, and o would only have chai. This is the same trick cout uses: operator<< returns ostream&.

Summary of the three keywords

  1. friend f(...) inside the class → f may read private data.
  2. A friend is not a member; only the class grants it; not inherited, not mutual.
  3. static data → one copy for the class; define it once outside (or inline static in C++17).
  4. static function → Class::f(); no object, no this, only static members.
  5. this → pointer to the object the call is on; this->x is the member.
  6. return *this (with a T& return type) → chained calls.

Common mistakes (and the real g++ messages)

Mistake Code What g++ says / what happens Fix
A non-member touching private data out << d.h; in operator<< error: 'int Duration::h' is private within this context friend ostream& operator<<(...); in the class
A static member declared but never defined static int next; only undefined reference to `Token::next' (linker) int Token::next = 1; outside, or inline static int next = 1;
A static function using a normal member static int issued() { return number; } error: invalid use of member 'Token::number' in static member function use only static members, or make it a normal member
A parameter hiding a member void setLimit(int limit) { limit = limit; } no message: the member stays 0 this->limit = limit;
Chaining a void function o.add(...).add(...) with void add error: invalid use of 'void' Order& add(...) { ...; return *this; }
Returning a copy instead of a reference Order add(...) no message: later adds go to temporary copies return Order&
Writing Duration:: on a friend's definition ostream& Duration::operator<<(...) error: it's not a member define it as a normal function

Mini project: a chai stall order counter

Each Order has its own id, item count and amount. The stall (the class) remembers the next order id and today's sales: two static members. add returns *this so calls can chain; two static functions report for the whole stall; operator<< is a friend defined inside the class, so it can print the private fields.

#include <iostream>
#include <string>
using namespace std;

class Order {
    int id, items = 0, amount = 0;
    static int nextId;
    static int sales;
public:
    Order() : id(nextId++) {}
    Order& add(int price) {
        items++; amount += price; sales += price;
        return *this;
    }
    static int orders() { return nextId - 1; }
    static int total() { return sales; }
    friend ostream& operator<<(ostream& out, const Order& o);
};
int Order::nextId = 1;
int Order::sales = 0;
ostream& operator<<(ostream& out, const Order& o) {
    out << "Order #" << o.id << ", items: " << o.items << ", Rs. " << o.amount;
    return out;
}

int main() {
    int n;
    while (cin >> n) {
        Order o;
        for (int i = 0; i < n; i++) {
            int price; cin >> price;
            o.add(price);
        }
        cout << o << endl;
    }
    cout << Order::orders() << " orders, Rs. " << Order::total() << endl;
    return 0;
}

Input:

2 15 20
1 30
3 15 15 25

Output:

Order #1, items: 2, Rs. 35
Order #2, items: 1, Rs. 30
Order #3, items: 3, Rs. 55
3 orders, Rs. 120

Each loop makes a fresh Order, but the stall remembers everything through its static members.

Practice

  1. Make Duration's operator+ a friend non-member instead of a member.
  2. Add a static reset() to Token for a new day, then issue tokens again from 1.
  3. Rewrite setLimit without this, using a different parameter name.
  4. A Chai class with chained withSugar(), extraHot() and show().
Solutions

1. As a friend, operator+ takes both operands and can read private h and m.

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    friend Duration operator+(const Duration& a, const Duration& b);
    friend ostream& operator<<(ostream& out, const Duration& d);
};
Duration operator+(const Duration& a, const Duration& b) {
    return Duration(a.h + b.h, a.m + b.m);
}
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.h << "h " << d.m << "m";
    return out;
}

int main() {
    cout << Duration(4, 45) + Duration(6, 30) << endl;
    return 0;
}

Output:

11h 15m

2. A static function can change static data.

#include <iostream>
using namespace std;

class Token {
    int number;
    static int next;
public:
    Token() { number = next; next++; }
    int num() const { return number; }
    static void reset() { next = 1; }
};
int Token::next = 1;

int main() {
    Token a, b;
    cout << "Monday: " << a.num() << " " << b.num() << endl;
    Token::reset();
    Token c;
    cout << "Tuesday: " << c.num() << endl;
    return 0;
}

Output:

Monday: 1 2
Tuesday: 1

3.

#include <iostream>
using namespace std;

class Card {
    int limit = 0;
public:
    void setLimit(int newLimit) { limit = newLimit; }
    int getLimit() const { return limit; }
};

int main() {
    Card card;
    card.setLimit(50000);
    cout << "Limit: " << card.getLimit() << endl;
    return 0;
}

Output:

Limit: 50000

4.

#include <iostream>
#include <string>
using namespace std;

class Chai {
    bool sugar = false, hot = false;
public:
    Chai& withSugar() { sugar = true; return *this; }
    Chai& extraHot() { hot = true; return *this; }
    void show() const {
        cout << "Chai" << (sugar ? ", with sugar" : "") << (hot ? ", extra hot" : "") << endl;
    }
};

int main() {
    Chai().withSugar().extraHot().show();
    Chai().extraHot().show();
    return 0;
}

Output:

Chai, with sugar, extra hot
Chai, extra hot

Quick quiz

What does this print?

#include <iostream>
#include <string>
using namespace std;

class Guest {
public:
    static int count;
    Guest() { count++; }
};
int Guest::count = 0;

int main() {
    Guest a, b;
    { Guest c; }
    Guest d;
    cout << Guest::count << " " << d.count;
    return 0;
}
  • A. 3 3
  • B. 4 4
  • C. 4 1
  • D. Linker error
Answer

B: 4 4 (verified). count is static: one copy for the class. Four Guests are created (a, b, c inside the block, d), so count is 4; c being destroyed doesn't subtract anything. d.count is the same shared variable. No linker error, because int Guest::count = 0; defines it.

Output:

4 4

Interview questions

  • What is a friend function? A non-member function that a class declares with friend, giving it access to the class's private and protected members.
  • Does a friend break encapsulation? Only in a controlled way: the class itself decides who its friends are, and they're listed in the class. It's often better than making data public or adding getters just for one function.
  • Is friendship inherited or mutual? Neither. A friend of a base is not a friend of the derived class, and A befriending B doesn't let A see B's privates.
  • What is a static data member? A member shared by all objects of a class: one copy for the class, existing even when no object exists. It must be defined once outside the class (or inline static since C++17).
  • Why do you get undefined reference for a static member? The class only declares it; without a definition (int Token::next = 1;) the linker can't find the variable.
  • What is a static member function? What can't it do? A function called on the class (Token::issued()), with no object and no this. It can't access non-static members, can't be virtual, and can't be const.
  • What is the this pointer? A hidden pointer passed to every non-static member function, pointing to the object the function was called on. Its type is T* (or const T* in a const member).
  • When do you need this explicitly? When a parameter or local hides a member (this->limit = limit), to return the object (return *this) for chaining, to pass the object to another function, or to check self-assignment (if (this == &other)).
  • Why does operator= return *this by reference? So assignments can chain (a = b = c) without copying, like built-in types.

Glossary

Term Plain meaning Example
Friend function A non-member function the class trusts with its private members friend ostream& operator<<(...);
Friend class A class whose every member function may access another class's private members friend class Bank;
Encapsulation Keeping data private and changing it only through the class's own functions private h, m
Static data member One variable shared by the whole class, not stored per object static int next;
Declaration Saying something exists (its name and type) static int next; inside the class
Definition Actually creating it (memory, starting value) int Token::next = 1;
Linker The build step that joins compiled pieces into one program; reports undefined reference missing Token::next
inline static C++17: define a static member inside the class inline static int next = 1;
Static member function A function of the class, called without an object; has no this Token::issued()
Scope resolution :: Names something inside a class or namespace Token::next, std::cout
this A pointer to the object a member function was called on this->limit
Shadowing (hiding) A local name or parameter hiding a member with the same name limit = limit
*this The object itself (dereferenced this) return *this;
Method chaining Calling several functions on the same object in one expression o.add(...).add(...)
Reference return Returning the object itself (T&) instead of a copy Order& add(...)

Summary

  • A non-member can't see private data ('int Duration::h' is private within this context). friend, written inside the class, grants access to one function; it's not a member, and friendship isn't inherited or mutual.
  • A normal member is one copy per object, so a per-object counter gives 1 1 1. static data is one copy per class; define it once outside the class, or the linker says undefined reference to `Token::next'.
  • A static function (Token::issued()) needs no object, so it has no this and can use only static members (invalid use of member ... in static member function).
  • this points to the object a call is on; this->limit = limit fixes a parameter that hides a member (which otherwise compiles and does nothing).
  • return *this with a T& return type lets you chain calls (invalid use of 'void' otherwise).

Next episode: an OOP project, a bank system: classes, encapsulation, inheritance, virtual functions, operators, friend and static, all in one real program.