In what cases can I use the above notation to initialize the object array in the above code?
Meaning usually we initialize the data members using the dot(.) operator or the constructor however, here they have used {‘id’, dead, profit} for each object in the array arr[ ] . What should be the template of the class to be able to use this notation?
And can I use it even if there are member functions declared inside the class?
Classes are exactly the same as structs except the default visibility is public in structs and private in classes. The above code would work as a class with two changes (changing struct to class and then adding public: before the variables). Having member functions doesn’t affect this at all.
#include <iostream>
using namespace std;
class Job {
private:
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit if job is over before or on deadline
public:
Job(char id, int dead, int profit) :
id(id),
dead(dead),
profit(profit)
{}
void hello() {
cout << id << " " << dead << " " << profit << endl;
}
};
int main() {
Job arr[] = {{'a', 1, 1}, {'b', 2, 3}};
for (size_t i = 0; i < 2; ++i) {
arr[i].hello();
}
return 0;
}
In short, you must have a corresponding constructor in your class.