classes

Why won't my code display the student id? I think I know why, but how could i fix it to show the id?
- thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<iostream>
#include<iomanip>


using namespace std;


class student
{
    private:
        string studentID;
        

    public:
        void setID(string);
        void setALL(string);
        void DisplayStudent();

};

int main()
{
    student student1;

    string studentID;

    student1.setID("AB123");
    return 0;
}

void student :: setID(string studentID)
{
    studentID = studentID;
}

void student :: setALL(string studentID)
{
    setID(studentID);

}

void student :: DisplayStudent()
{
    student(setALL);
    cout << studentID;
}
A few things.

- line 33 does nothing; your member variable is hidden by the parameter. Either rename your member variable to m_studentID, or do this->studentID = studentID instead.

- What's the point of student::setALL?

- line 44 shouldn't compile... it doesn't even make sense. What were you trying to do there anyway? Just get rid of it; a function called 'DisplayStudent' should do nothing else except print the student data, and thus should be marked const.

- Notably, you never actually call your student::DisplayStudent function anyway, so it's not going to print anything regardless.

EDIT:
Here's it fixed up:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

class Student {
    public:
        void setID(std::string id) {
            m_id = id;
        }

        void display() const {
            std::cout << m_id << '\n';
        } 

    private:
        std::string m_id;
};

int main() {
    Student student1;

    student1.setID("AB123");
    student1.display();

    return 0;
}
Last edited on
the setall function is supposed to initialize the class members.

thank you! Sorry about that.
Topic archived. No new replies allowed.