0

I need help with my cpp project.

I have a class Item with a variable for ID that should assign a new ID (add one onto the previous value) but every time I call the function it assigns the same value (1)

class Item{
private:
    int Unique_ID = 0;
    int* ID_pointer = &Unique_ID;
};

void Item::New_Item(){
    Item n;
    *ID_pointer += 1; 
    std::cout << "Unique ID code created for this item is: " << Unique_ID << "\n";
}

When I call this function again to add another item and write the info in the text file the ID is 1 for every new item. How can I fix this? I hope this is enough info (this is my first post and I'm new to this) Thanks

EDIT: https://godbolt.org/z/N-DyC_ link to my code if that helps because i feel like im not explaining it well im making a shop management system that writes information to a text file.

dantrg
  • 1
  • 2
  • 2
    Do you know what `static`-ly scoped objects are, and how to use them? If yes, then what exactly is your question. If no, then see your C++ textbook for more information and a full explanation. – Sam Varshavchik Apr 17 '20 at 12:15
  • Have you tried putting `static` in front of `int` in your declaration as in `static int Unique_ID = 0`? – F Trias Apr 17 '20 at 12:24
  • @FTrias Trials When I try this i get the following error message: "a member with an in-class initializer must be const" Never used or heard of statically scoped objects so I'll look into the topic – dantrg Apr 17 '20 at 12:31
  • Maybe this will help: https://stackoverflow.com/questions/16329962/why-can-in-class-initializers-only-use-or – F Trias Apr 17 '20 at 12:41
  • [Works for me](https://gcc.godbolt.org/z/zGqVXz). – Raymond Chen Apr 17 '20 at 13:05

1 Answers1

-1

This code will increment the ID and make them unique :

#include <iostream>
using namespace std; 

class Item {
private:
    int Unique_ID = 0;
    int* ID_pointer = &Unique_ID;
public:
    void New_Item();
};

void Item::New_Item() {
    *ID_pointer += 1;
    cout << "Unique ID code created for this item is: " << Unique_ID << "\n";
}
int main() {
    Item one;
    one.New_Item();
    one.New_Item();
    one.New_Item();
    system("pause");
}

Result:

enter image description here

  • Hi. Unfortunately, the new values aren't stored anywhere. They're lost as soon as a new ID is generated. – Spencer Apr 17 '20 at 14:19
  • dantrg just wanted to generate unique id. if he wants to store it he can create some other function which read and write file. Regardless the main question was just to generate unique id. it would be great if you could undo your downvote. – Muhammad Ahmed Apr 17 '20 at 15:04