class Student
{
public: //add any needed functions yourself
private:
string name;
int rollnumber;
}
class University
{
public:
// constructor
private:
int numberOfStudents;
SList<Student*> *list; // list is developed by me as a linked list but what is this Student* here, instead of just Student???
}
I have seen things like SList<Student> *list
, so I can create a new list in the constructor by saying list = new SList<Student>;
But here, it doesn't work due to Student*
. What should I do, and what will be the syntax to declare it?
CodePudding user response:
Just as SList*
is a pointer to an SList
, Student*
is a pointer to a Student
. If you want to new
an SList
of Student*
pointers, it would look like this:
SList<Student*> *list;
...
list = new SList<Student*>;
...
delete list;
As such, you will likely also need to new
and delete
every Student
that you want to store in the list.
SList<Student*> *list;
...
list = new SList<Student*>;
...
list->Add(new Student);
...
for (each student in the list)
delete student;
delete list;
In modern C , if you need to use pointers to objects in dynamic storage, you should strive to avoid using new
and delete
manually at all. Make use of smart pointers instead, like std:unique_ptr
/std::make_unique()
and std::shared_ptr
/std::make_shared()
.
std::unique_ptr<SList<std::unique_ptr<Student>> list;
...
list = std::make_unique<SList<std::unique_ptr<Student>>>();
...
list->Add(std::make_unique<Student>());
...
// no need for delete...
Of course, you should prefer not to use dynamic storage at all when you can avoid it.
SList<Student> list; // no need for new...
...
list->Add(Studen()); // no need for new...
...
// no need for delete...
CodePudding user response:
You want to create a SList of pointers in heap and want your variable "list" to point at that list so, I think you need to make that variable a double pointer.
SList<Student*> **list;
*list = new SList<Student*>;