cout object

Why when this code is running compiler is not stopping.
I know I can return name in class instead of print out here and cout it in main but
curious what is different?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

class Job{
private:
    string name;
public:
    void setName(string x){
        name = x;
    }
    string getName(){
        cout << name;
    }

};

int main() {
    Job a;
    a.setName("Software Eng.");
    a.getName();

}
Last edited on
> Why when this code is running compiler is not stopping.

The program has undefined behaviour. The function must return a string.
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function. - IS


1
2
3
4
    string getName(){
        cout << name;
        return name ; // *** added
    }
and if you just want to print it without returning anything...
make it a void instead of a string...
closed account (48T7M4Gy)
Good practice with class design with respect to portability/reusability indicates/dictates that getters and setters preferably shouldn't be system/platform dependent.

What this means is getName not only should clearly return a string but the cout is better placed in main. So the statement in main() would be:

cout << a.getName() << endl; etc
Topic archived. No new replies allowed.