Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use use properly in std:ostream& member, while "this" is a const?

Tags:

c++

ostream

I have a class named "Subscriber" , which is inherited from a class named "Client", which contains the following lines of code , in "protected" :

std::ostream& messagesSink;

std::ostream&  getMessagesSink() {
    return messagesSink;
}

(messagesSink is initialized in the constructor of Subscribers)

and there is the following function-member in "subscriber" :

virtual void recieveMessage(const std::string& message ,
        const Topic& topic,
        const Client& client) const {
    messagesSink << "Topic: "<< topic
            << ". Sender: #" << client.getId() << ". Reciver: #"
            << getId() << ".Message: " << message;
}

the problem goes like this:in his current state, the code has no compilation errors, but if I replace the use of the member messagesSink in the function getMessagesSink(), as the code below, compilation errors appears:

virtual void recieveMessage(const std::string& message ,
        const Topic& topic,
        const Client& client) const {
    getMessagesSink() << "Topic: "<< topic
            << ". Sender: #" << client.getId() << ". Reciver: #"
            << getId() << ".Message: " << message;
}

my questions are:

1) what is the diffrence between before and after?

2) how to use properly the refrence to std::ostream ,while in a function that keeps "this" as a const?

like image 231
Eden_Yosef Avatar asked Jan 17 '26 13:01

Eden_Yosef


1 Answers

The problem is that getMessagesSink is not marked const. receiveMessage is marked const so it can't call non-const member functions.

like image 105
Pete Becker Avatar answered Jan 20 '26 04:01

Pete Becker