How to differate two default constructors or some other solution.

I have class student


1
2
3
4
5
6
7
8
9
Student{
public:
   Student(){
      id = idCounter++;
   }
private:
    static int idCounter;
    int id;
}


but when I want to do:
 
Student *list = new Student[10];


and then:

 
list[0] = Student(); // this students id will be 10 or 11 


I wrote this for you to see. Those classes I have are very long that why I didnt add them here.

So how can I avoid this? One way would be make different constructors, but that seems to be bad idea.


When you create the array it will automatically create all Student objects in it using the default constructor, so no need to do things like list[0] = Student();.
Last edited on
Yes but my counter skyrockets. How can I avoid it?
Im creating two classes one is something like vector and second is student. And I need to my vectorish object hold student objects.
Last edited on
Well, you could create less objects...

Do you understand what list[0] = Student(); is doing? First a temporary object of type Student is created using the default constructor. The temporary object is then assigned to the already existing object list[0]. This means that list[0].id will be set to the id of the temporary object. And then, before the statement ends, the temporary object is destroyed. What happens is similar to this:
1
2
3
4
{
	Student tmp;
	list[0] = tmp;
}

So, can't you just avoid doing this?

If that is not an option, well maybe you should move the id generation to a function instead so that you can do: list[0].giveUniqueId();
Last edited on
I understand what you are saying, but then how I should be making my list(vectorish) class?
Now it is :

1
2
3
4
5
6
7
8
9
template <class T> 
List{
private:
    T* _list;
public:
    List(){
       _list = new T[10];
    }
}


basically its like this, but size can change. When I add new values and _list is full then it creates new pointer with holds more T types.
You could use placement new. Learn about it if you are interested. Not really a beginner subject though.
Topic archived. No new replies allowed.