How to use static data member in a class using C++

1 Answer

0 votes
#include <iostream>

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

class Box {
private:
	double length;
	double width;
	double height;
public:
	static int cCounter;

	Box(double l, double w, double h) : length(l), width(w), height(h)
	{
		cout << "Box(double l, double w = 1.0, double h = 1.0) Constructor" << endl;
		cCounter++;
	}
	Box()
	{
		cout << "Box() constructor " << endl;
		length = width = height = 1.0;
		cCounter++;
	}
	double Volume() const
	{
		return length * width * height;
	}


};

int Box::cCounter = 0;

int main()
{
	Box box_array[3];
	Box b(7.0, 3.0, 2.0);

	cout << "box_array[0].cCounter = " << box_array[0].cCounter << endl;
	cout << "box_array[0].Volume() = " << box_array[0].Volume() << endl;
	
	cout << "box_array[1].cCounter = " << box_array[0].cCounter << endl;
	cout << "box_array[1].Volume() = " << box_array[0].Volume() << endl;

	cout << "Box::cCounter = " << Box::cCounter << endl;
	cout << "b.Volume() = " << b.Volume() << endl;

	return 0;
}


/*
run:

Box() constructor
Box() constructor
Box() constructor
Box(double l, double w = 1.0, double h = 1.0) Constructor
box_array[0].cCounter = 4
box_array[0].Volume() = 1
box_array[1].cCounter = 4
box_array[1].Volume() = 1
Box::cCounter = 4
b.Volume() = 42

*/

 



answered Mar 11, 2018 by avibootz
edited Mar 11, 2018 by avibootz

Related questions

1 answer 192 views
1 answer 182 views
1 answer 112 views
1 answer 172 views
...