make member variable immutable after constractor

In other langs like Java there are keywords like 'final' where a member variable suffixed by 'final' is immutable after the construction of the object

I know C++ has the 'Const' but it required a variable's value to be set during declaration (not creation)

Note: the Variable should also be mutable during the deconstractor (do not want to be forced to leak memory)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct X{
	const int f;
	X create(int i){
		X x;
		x.f = i;
		return x;
	}
};

int main() {
	X x.(5);
}

}
Last edited on
Umm, what?
1
2
3
4
5
6
7
8
struct X{
	const int f;
	X( int i ) : f(i) {}
};

int main() {
	X x(5);
}
@keskiverto is it possible to set the value of f in the curly braces ({})
for example if I want to set the value f based on a branch operation or i through reading a file, how would I go about it
Thanks
Last edited on
You can use ternary operator, or factor out more complicated logic into a function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int foo(int i)
{
    if (i % 2 == 0)
    {
        return 42;
    }
    else
    {
        return 1729;   
    }
}

struct X{
	const int f;
	X( int i ) : f(foo(i)) {}
};

int main() {
	X x(5);
}
As an example of using ternary:

1
2
3
4
5
6
7
8
struct X {
	const int f;
	X(int i, bool b) : f(b ? i : i * i) {}
};

int main() {
	X x(5, true);
}


as an example of using an immediate lambda:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <fstream>

struct X {
	const int f;
	X(const std::string& fn) : f([&fn]() {std::ifstream ifs(fn); int i {}; ifs >> i; return i; }()) {}
};

int main() {
	X x("test.txt");
}


Last edited on
Is there a Reason as to why const variable can not be altered inside the constructor's {} also how to free it if I have to in the destructor's {}

P.S. I have previously marked this thread as solved, but I realized I have a few more questions
Last edited on
cause it's const! const variables can only be initialised as they are defined.

Just use delete as would normally. However, having a pointer to const isn't often that helpful as the memory to which it points can't be changed. You can have a const pointer to memory.

1
2
3
4
5
6
struct myclass {
	int* const ptr {};  // const pointer to amendable memory

	myclass() : ptr(new int[10]) {}
	~myclass() { delete[] ptr; }
};

Last edited on
Just make the member variable private. Then your member access arrangements will control what you can do to that variable (setting it in the constructor; doing whatever you want to do in the destructor).
is there a way make a variable immutable after it's initialized and not it's declaration
No.

A variable can only be set as const when it is defined. You can't define, set it's value with say an assignment and then set it as const.

Topic archived. No new replies allowed.