-2

I had declared a static variable "id" which is incremented with static function but in the output it is displaying same value everytime. I have attached the output image .

`

class student
{
public:
    string name;
    static int id;
    char sec;
    student()
    {
        sec = 'A';
    }
    static int st_id()
    {
        id++;
        return id;
    }

    void st_name()
    {
        cout << "Enter student name:";
        cin >> name;
    }
};
int student ::id = 0;
int main()
{
    int num, i;
    cout << "Enter the no. of students in class :";
    cin >> num;
    student *p = new student[num];
    for (i = 0; i < num; i++)
    {
        p[i].st_name();
    }
    cout << endl
         << "  NAME         ID        SEC" << endl;
    for (i = 0; i < num; i++)
    {
        cout << i + 1 << ")"
             << " " << p[i].name << "           " << p[i].st_id << "         " << p[i].sec << endl;
    }
}

`

Output image :

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 3
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Dec 08 '22 at 14:26
  • Also `C` and `C++` are different languages. Tag only which is related to your question. – Jason Dec 08 '22 at 14:27
  • Why did you use a `static` class member variable for the `id`? That sounds quite odd, if not nonsensical. – πάντα ῥεῖ Dec 08 '22 at 14:28
  • Refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) like [C++ Primer by Lippman 5th edition](https://zhjwpku.com/assets/pdf/books/C++.Primer.5th.Edition_2013.pdf). – Jason Dec 08 '22 at 14:28
  • `p[i].st_id` is not a function call. Also even if it was corrected you will also need a class member variable to hold the id. – drescherjm Dec 08 '22 at 14:29
  • 1
    (What’s up with those single backticks in the question? I’ve seen them a lot lately. Is the question editor broken?) – Biffen Dec 08 '22 at 14:29
  • If you are using static to count the number of instantiations, you should also use another non-static member to save the id. Assuming that you know what `static` means, there. – Bob__ Dec 08 '22 at 14:29
  • 1
    I suppose you want what is now called `id` to be a counter, call it `counter`, and then everytime a new student is created you want to assign it a unique `id` based on the `counter`. You have the first part of counting how many students are there almost, but the second part is missing completely. The `id` should be per `student` only the `counter` should be static – 463035818_is_not_an_ai Dec 08 '22 at 14:30

1 Answers1

2

When you write, << p[i].st_id, it doesn't call the function; instead, it prints the member function pointer. To call it, you need << p[i].st_id().

lorro
  • 10,687
  • 23
  • 36