Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to use and initialize array of classes in C++

2 Answers

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Box {
public:
	Box(double _length, double _width = 1.0, double _height = 1.0) :
		length(_length),
		width(_width),
		height(_height)
	{}
	Box() 	{
		length = width = height = 1.0;
	}

	void Print() 
	{
		cout << length << " " << width << " " << height << endl;
	}	
	double Volume() const
	{
		return length * width * height;
	}
private:
	double length;
	double width;
	double height;
};

int main()
{
	Box arr[3]
	{
		Box(1, 2, 3),
		Box(2, 4, 6),
		Box(1.2, 3.5, 6.7)
	};

	arr[0].Print();
	arr[1].Print();
	arr[2].Print();

	cout << arr[0].Volume() << endl;
	cout << arr[1].Volume() << endl;
	cout << arr[2].Volume() << endl;
	
	return 0;
}


/*
run:

1 2 3
2 4 6
1.2 3.5 6.7
6
48
28.14

*/

 



answered Mar 28, 2018 by avibootz
0 votes
#include <iostream>

using std::cout;
using std::endl;

class Box {
public:
	Box(double _length, double _width = 1.0, double _height = 1.0) :
		length(_length),
		width(_width),
		height(_height)
	{}
	Box() 	{
		length = width = height = 3.0;
	}

	void Print() 
	{
		cout << length << " " << width << " " << height << endl;
	}	
	double Volume() const
	{
		return length * width * height;
	}
private:
	double length;
	double width;
	double height;
};

int main()
{
	Box arr[2];

	arr[0].Print();
	arr[1].Print();

	cout << arr[0].Volume() << endl;
	cout << arr[1].Volume() << endl;
	
	return 0;
}


/*
run:

3 3 3
3 3 3
27
27

*/

 



answered Mar 28, 2018 by avibootz

Related questions

1 answer 220 views
1 answer 177 views
177 views asked Mar 12, 2021 by avibootz
1 answer 181 views
1 answer 225 views
1 answer 220 views
1 answer 151 views
1 answer 209 views
...