0

I'm trying to practice basic constructor problems and ran into this issue. It should display "unknown" when no string is passed. Here is my code:

#include <iostream>
#include<string>

class Student{

private:
std::string name{};

public:
Student() : name{"unknown"}
{};
Student(std::string s){
    
    name = s;
}
void get_name(){
    
    std::cout<<name; 
}

};


int main(){

Student student;
std::cout<<"Default name is: "<<student.get_name<<std::endl;
Student custom_student("adam");
std::cout<<"Custom name is: "<<custom_student.get_name<<std::endl;
return 0;

}
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Sampath P
  • 39
  • 3
  • Hi, welcome to SO. You can overload the ostream operator, see this [possible soution](https://stackoverflow.com/q/476272/2030219) which tells you how to do it. – Joel Aug 27 '22 at 00:14

1 Answers1

0

You've programmed as if your class member functions return a value. They don't. They are void. You can't do std::cout << something_void.

#include <iostream>
#include <string>
#include <utility>

class Student {
   private:
    std::string name{};

   public:
    Student() : name{"unknown"} {};
    Student(std::string s) : name(std::move(s)) {}
    void get_name() { std::cout << name; }
};

int main() {
    Student student;
    std::cout << "Default name is: ";

    // doesn't return anything but prints directly:
    student.get_name();

    Student custom_student("adam");
    std::cout << "Custom name is: ";

    // doesn't return anything but prints directly:
    custom_student.get_name();

    return 0;
}

What you probably wanted is to return the value from the object:

const std::string& get_name() const { return name; }`

This kind of return would then have been useful in your code.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108