Home > other >  Can we use a class in C the same as a struct in C?
Can we use a class in C the same as a struct in C?

Time:12-10

I used to program in C and I moved to C after learning OOP. I am trying to use the things I learned in my new project.

I am working on a school management project. If I want to add 1 student, I can use the constructor:

Student student1 = Student(string firstname, string lastname, int Age, char Gender, int group);

That would work fine in adding 1 student, but if I want to add more then 1 student using a loop, how can I do it?

In C, we use a struct to do this:

struct student{...};
struct student students[n] //n: number of student i want to add
for(int i=0;i<n;i  ){
   students[i].name = ...; 
}

Is there a way to achieve this in OOP (I am new in using OOP)?

CodePudding user response:

Yes, you can do the same kind of loop in C . Except, you need to use new[] to create the array, as variable length arrays are not part of standard C .

class student{...};

student *students = new student[n];
for(int i=0;i<n;i  ){
   students[i].name = ...; 
}
...
delete[] students;

A better option is to use std::vector instead and let it handle the array management:

#include <vector>

class student{...};

std::vector<student> students(n);
for(int i=0;i<n;i  ){
   students[i].name = ...; 
}
...
  • Related