Initializing objects

class Job
{
public:
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit if job is over before or on deadline
};

int main()
{
Job arr[] = { { ‘a’ , 2, 100}, { ‘b’ , 1, 19}, { ‘c’ , 2, 27}, { ‘d’ , 1, 25}, { ‘e’ , 3, 15}};`
}

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.

1 Like

I have changed it to ‘class’ for better clarity. And please check out the question again, this ain’t what I’m asking?

Here is a example:

#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.

2 Likes

Hello,

You’re asking about aggregate-initialization, which is a specialized form of list initialization.
You can read https://en.cppreference.com/w/cpp/language/aggregate_initialization and https://en.cppreference.com/w/cpp/language/list_initialization to understand all the cases.

In short, it is very handy for POD structs.

2 Likes

Hey! Thanks. That was helpful. :slight_smile:

Thanks! That was helpful. :slight_smile: