1

I've got a basic question. Is it possible to number objects automatically? So for example if I have a class 'item' and in the main I have

item item1(weight, length);
item item2(weight, length);

and in the constructor of the item class we assign the weight and length to the corresponding variables.

class item {

public:
item(int w, int l){
weight = w ;
length = l ;
itemnumber = ??? ;

private:
int weight;
int length;
int itemnumber;
};

But on top of that I also want a variable itemnumber. This itemnumber should be 1 the first time I create an object (so 1 for item1) and 2 the second object created (item2) and so on. But I don't want to pass it as a parameter. So basically what should I put instead of the '???' in my code ?

Is this possible?

2 Answers 2

3

Create a static field inside class, and increment it in constructor.

something like this:

class A {
public:
    A() : itemnumber(nextNum) { ++nextNum; }
private:
    int itemnumber;
    static int nextNum;
}

// in CPP file initialize it
int A::nextNum = 1;

Also, don't forget to increment static field in copy and move constructors\operators.

Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget to increment it in the copy/move constructor too!
@Rakete1111 Hope it's not too late but what exactly do you mean by increment it in copy/move constructor?
@PieterDe Nope, not too late :) When you copy an object, the copy constructor is called, which copies the object, i.e. A a; A b = a; Now if you don't increment nextNum in the copy constructor, then both a and b will have the same itemnumber, which isn't good.
0

with a static variable like

class rect{
public:
static int num;
rect(){num++;}
};

int rect::num =0;
int main(){
rect a();
cout << rect::num;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.