Constructor and Copy constructor for a class

Mar 4, 2017 at 6:54am
Hello everyone, I have a very basic questions on creating a constructor and copy constructor for a class that I created. I was wondering if the Sets.cpp file is correct, if not can anyone explain to me please. Much appreciated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Sets header file
  class Sets {
private:
	int size;
	int arr[20];
public:
	Sets();
	Sets(int max);
};
//Sets .CPP files
Sets::Sets()
{
	arr[20] = arr[size];
}
Sets::Sets(int max)
{
	size = max;
	arr[size] = arr[max];
}
Mar 4, 2017 at 9:06am
1
2
3
4
Sets::Sets()
{
	arr[20] = arr[size];
}

You're accessing index 20 of arr, which is out of bounds and accessing index size, which is uninitialised, both leading to undefined behaviour. Likewise with your overloaded constructor.

copy constructor

There aren't any copy constructors that you have defined. Sets::Sets(int max) is an overloaded constructor.
Mar 4, 2017 at 11:35am
You are having an array of size 20 so it's final index is going to be 19, mark that.
Array's index will always start from 0 up to n-1 when n is the size you gave when you created it.
As you will keep on programming those thing will be obvious to you. If you still have those kind of problems you can use any code security program to help you code, such as Checkmarx that does a great job I heard. This should lead you to a better code.
Good luck!
Ben.
Topic archived. No new replies allowed.