0

I am currently studying C++ as a beginner. There is this program that simulates a printing queue but I don't quite understand what the code means inside the class that contains data members.

#include <iostream>
#include <queue>

class Job
{
    int id;
    std::string user;
    int time;
    static int count;

public:
    Job(const std::string &u, int t) : user(u), time(t), id(++count)
    {
    }

    friend std::ostream &operator<<(std::ostream &os, const Job &j)
    {
        os << "id: " << j.id << ", user: " << j.user << ", time: " << j.time << " seconds" << std::endl;
        return os;
    }
};

Can anybody explain what's happening in that code below? I don't understand what the code such as below does:

Job(const std::string &u, int t) : user(u), time(t), id(++count)

  • `Job(const std::string &u, int t) ` - this defines the constructor which takes 2 arguments. `: user(u), time(t), id(++count)` - is the initialization code for u, t and id. What else would you like to know ? – moi Sep 11 '21 at 07:45
  • [A couple of decent books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) might be helpful as well. And learning the basics before you attempt to understand other peoples code. – Some programmer dude Sep 11 '21 at 07:49
  • I would like to know what `friend std::ostream &operator<<(std::ostream &os, const Job &j)` does since `std::ostream` and friend functions are still new to me. Thank you! – Sway the Destroyer 'STD' Sep 11 '21 at 07:49
  • Btw: contrary to the title your class does not contain any public member variables. The default visibility of symbols in a `class` is `private`. – fabian Sep 11 '21 at 07:50
  • As for the operator definition, it's case (2) here: https://en.cppreference.com/w/cpp/language/friend You define the `<<` operator for a reference to `std::ostream` as left parameter and a reference to a (possibly const) `Job` as right parameter. This function is part of the namespace scope, but it's a friend of `Job` and therefore has access to all of it's members (even the private ones). – fabian Sep 11 '21 at 07:55

0 Answers0