-
OOP Basics
Hi, I am a first semester student, learning the OOPs basics. I need help for a program:
Code:
class Message{
public:
void input();
int output();
private:
long token_number;// next token to be given to client
};
void Message::input()
{
token_number = 1;
}
int Message::output()
{
return token_number;
}
I dont know the right way to call these elements in the main()
int main(){
Message obj;
std::cout<< out_buffer<<obj.output()<<std::endl;//write the token number in the buffer
std::cout<<"Response received"<<++obj.input();//To update the input value and display
}
-
Re: OOP Basics
What is out_buffer?
I'm not sure what you're trying to achieve. Perhaps you could be more explicit in the requirements? However consider:
Code:
#include <iostream>
class Message {
public:
void input();
int output() const;
Message& operator++() {
++token_number;
return *this;
}
private:
long token_number {};
};
void Message::input() {
token_number = 1;
}
int Message::output() const {
return token_number;
}
int main() {
Message obj;
std::cout << "Response received " << (++obj).output() << '\n';
std::cout << "Response received " << (++obj).output() << '\n';
}
which displays:
Code:
Response received 1
Response received 2
-
Re: OOP Basics
Why is there curly braces after the token_number ?
-
Re: OOP Basics
This is default value initialisation. If there's no value between the {} the variable is initialised to the default value for the type of the variable - which is 0 for long. It's good practice to initialise variables when they are defined. Variables of a class type should be initialised via their default constructor/constructors.
See https://en.cppreference.com/w/cpp/la...initialization