const behaviour in class

Question

why compiler doesn't complain for d in below code?
Even d will need constant address, that should be know before Ctor ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 class Test{
private:
                static const int a;
                const int b;
                int* const c;
                int const * d;
public:
                Test(int i) //: i(b) compiler will throw Error
                {
                                // it will throw error only for b,
                                // if i initialize b before Ctor call,
                                // compiler will not throw error
                }
               
 
};


Last edited on
I have understood neither your question nor your code snip.
vlad from moscow ...i have few valid combination of const in the above example.

if i initialize Test::b after ctor call, compiler will throw Error.(which is correct behaviour )

now what i have studied that compiler will optimize the code by not creating storage for const(conditionally), it just fold it from symbol table.

Now my question is, in case of Test::d compiler need to create storage as it is pointing to constant location. How compiler will handle this.

is it not necessary that we initialize it before ctor call?
Last edited on
@ankushnandan
if i initialize Test::b after ctor call, compiler will throw Error.


You may not assign a value to a const object.

@ankushnandan
now what i have studied that compiler will optimize the code by not creating storage for const(conditionally), it just fold it from symbol table.


The compiler must allocate a memory for b because b is a non-static data member of the class.

@ankushnandan
Now my question is, in case of Test::d compiler need to create storage as it is pointing to constant location. How compiler will handle this.


The pointer itself is not constant so the compiler need not to create storage and assign its address to the pointer.
d is a non-const pointer to const int. AS with other non-const data members you don't need to initialize them in the constructor initialization list.

If you change the type of d to int const * const you will notice the difference.
@ vlad from moscow

The compiler must allocate a memory for b because b is a non-static data member of the class.

i guess compiler will create storage only if we force it to( like if we use &b). but in above case it will not.

The pointer itself is not constant so the compiler need not to create storage and assign its address to the pointer.

i guess d is a pointer to constant location. the value that location holds can be changed but not the location. So compiler will force the storage creation
All your assumptions are wrong.
@Peter87 and vlad from moscow

Thanks i got it .
Topic archived. No new replies allowed.