Hi guys, I'm new and self teaching myself C++. A problem from the book says to create the CandyBar Struct and the create a dynamic array that hold 3 structures, initialize the structures and output each of them. The code works BUT I'm wondering if there is an easier way to initialize each variable or am i stuck with the "sn[0].brandName = ..." way to initialize everything?

struct CandyBar
	{
		string brandName;
		float weight;
		int calories;
	};

	CandyBar* sn = new CandyBar [3]; 

        sn[0].brandName = "snickers";
        sn[0].weight = 2.2;
        sn[0].calories = 147;
	
	cout << sn[0].brandName << sn[0].weight << sn[0].calories << "\n";
//	cout << sn[1].brandName << sn[1].weight << sn[1].calories << "\n";
//	cout << sn[2].brandName << sn[2].weight << sn[2].calories << "\n";
delete [] sn;

Yes there is: Use constructors. I think you will learn about them a bit later:

struct CandyBar
	{
		string brandName;
		float weight;
		int calories;
		
		//no argument constructor
		CandyBar(){}
		
		//a argumented constructor
		CandyBar(string bn, float w, int cal):
		brandName(bn), weight(w), calories(c) {}
		
	};
	
//in main()
CandyBar* cb= new[3];
cb[0]=CandyBar("snickers",2.2,147);
cb[1]=CandyBar("nickers",4.22,1447);
cb[2]=CandyBar("kers",7.22,447);

//print all of these

why did you change

CandyBar* cb = CandyBar new[3];

to

CandyBar* cb = new[3];

How will the compiler know what type the array of 3 is?

Is that implicitly defined by the fact that cb is of type CandyBar?
and because something of one type must point to something else that is of the same type?

>why did you change
Answer; I was in a hurry. I wanted to give you the main point about constructors. :)
spare me if you could

Member Avatar for jencas

And you should think about overloading operator << for CandyBar to allow stream output:

ostream& operator << (ostream& os, const CandyBar& bar)
{
  os << bar.brandName << " " << bar.weight << " " << bar.calories << endl();
}

See also: http://gethelp.devx.com/techtips/cpp_pro/10min/10min0400.asp

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.