Difference between VS 2015 and cpp.sh

Hi, lets ignore the fact that this is very bad matrix class. The elements are being allocated in the line no matter what the dimensions are. I just tried to create operator[]() for fun and optional member function default_init() that initializes every element to default. So it can be used if elements actually have default value.

On visual studio this code dont really work because when I cout << elements in main() they have all kinds of random values.

If I run this on cpp.sh that every element is correctly initialized to its default value 0.

Why exactly this is happening? Problem in code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

template<class T>
class Matrix {
	int dim1;
	int dim2;
	int sz;
	T* elem;
public:
	Matrix(int d1, int d2) : dim1{ d1 }, dim2{ d2 },
		sz{ dim1 * dim2 }, elem{ new T[sz] } {}
	~Matrix() { delete[] elem; }


	int size() { return sz; }
	void default_init();
	T& operator[](int);
};

1
2
3
4
5
6
7
template<class T>
void Matrix<T>::default_init(){
	T* p = elem;
	for (int i = 0; i < sz; ++i) {
		*p = T{};
	}
}

1
2
3
4
5
template<class T>
T& Matrix<T>::operator[](int index) {

	return *(elem + index);
}

1
2
3
4
5
6
7
8
9
10
11
12
int main() {

	Matrix<int> m{ 1,6 };
	m.default_init();

	std::cout << m[0] << std::endl;
	std::cout << m[1] << std::endl;
	std::cout << m[3] << std::endl;
	std::cout << m[4] << std::endl;
	std::cout << m[5] << std::endl;

}


Output VS 2015
0
-842150451
-842150451
-842150451
-842150451
-842150451


Output cpp.sh
0
0
0
0
0
0
Last edited on
You initialize p to point at the first element in the array. p is never changed so only the first element is set to zero.
ohh man I'm so ashamed of myself. Thank you man! Don't have idea why it worked on cpp.sh
I'm sry for posting this. :(
Last edited on
It didn't work on cpp.sh ; on cpp.sh, you only set the first to zero. The other values could be anything at all. On cpp.sh, it seems that they happen to be zero.
Last edited on
Ohh yea just checked it out with other number instead of default. Thanks man!
Topic archived. No new replies allowed.