class member as const

Hi All,

Can I specify class member as const just like Java?

This is correct Java snippet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class TestFinals
{
    private final int n = 77;
    TestFinals(int val)
    {
        n = 8;
    }
    public int getN()
    {
        return n;
    }
    public void setN(int val)
    {
        //n = 8;
    }
    public static void main(String[] args)
    {
        TestFinals tf = new TestFinals(9);
        System.out.println("the value of n is " + tf.getN());
    }
}


This is incorrect C++ snippet but it's similar to Java snippet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

class TestConst
{
private:
	const int n = 77;
public:
	TestConst(int val)
	{
		n = 8;
	}
	int getN()
	{
		return n;
	}
	void setN(int val)
	{
		//n = 8;
	}
};

int main()
{
	TestConst tc(9);
	cout<<"the value of n is "<<tc.getN();
	return 0;
}
Last edited on
In C++ you can use enum within a C++ class to simulate a constant within a Java class.
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

class TestConst
{
private:
    const int n;
public:
    TestConst(int val)
        : n(val)
    {
        //n = 8;
    }
    int getN()
    {
        return n;
    }
    void setN(int val)
    {
        //n = 8;
    }
};

int main()
{
    TestConst tc(9);
    TestConst tc2(10);
    cout<< "TestConst tc::n = "<<tc.getN() << endl;
    cout<< "TestConst tc::n = "<<tc2.getN() << endl;
    return 0;
}
Last edited on
Thanks a lot, Grey this is exactly what I'm looking for
Topic archived. No new replies allowed.