Assigning value to constant integer in Class

Hello, I just started making the following program,

1
2
3
4
5
6
7
8
9
10
Make a class Pointer
Declare a 2D integer pointer as private data member in it. And a const int size. 
Make a default constructor o Initialize 2D pointer with size [10][10]. o Assign size = 10.
Make a parameterized constructor which will take size as parameter; initialize 2D pointer with size passed as parameter in the constructor. 
Assign size with the size passed as parameter.
Make a driver function in which you are supposed to make an object using default constructor and an object using parameterized constructor.

Restrictions

All data members should be private


So, to start, I declared a double pointer and a const int by the name of size (I didn't initialize it, only declared it) and then made a constructor in which I assigned a value 10 to the const int size...
1
2
3
4
5
6
7
8
9
10
11
12
13
  #include <iostream>
using namespace std;
class Pointer {
	int **p; 
	const int size; 
public:
	Pointer()
	{
		size = 10; 
		int **p = new int *[size];

	}
};


However, the line, "size = 10;" is showing error and it is saying that the "expression must be a modifiable lvalue"
Why is that? Because I didn't initialize the const int on the time of declaration and this is the first value I am assigning to this int. So, why is it showing the error?

and if so, then how can I fulfill the condition of the question that I must assign the value of size in the constructor (in default constructor as well as a parameterized constructor where size will get a different value)
Can anybody help? Thank you!
Last edited on
You cannot assign to a constant. You need to initialize it using the member initializer list.
I believe this is the syntax you want:

class A
{
const int b;
A(int c) : b(c) {} //the constructor of A sets the constant for THIS instance to the input
};



1) Please note in your constructor you're assigning to a local variable.

2) You could also opt for the in-class initializers, which happen to be the suggested syntax in the C++ Core Guidelines:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c48-prefer-in-class-initializers-to-member-initializers-in-constructors-for-constant-initializers
Last edited on
Thank you. Problem is solved by the use of list initialization. :)
Also if you're using modern C++ you could assign the value in the definition:

1
2
3
class Pointer {
	int **p; 
	const int size = 100; 
Topic archived. No new replies allowed.