Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: Pointers within Const Struct

How do I force const-ness of the memory pointed to by obj->val1 in the function fn?

#include <iostream>

struct foo {
    int* val1;
    int* val2;
    int* val3;
};

void fn( const foo* obj )
{
    // I don't want to be able to change the integer that val1 points to
    //obj->val1 = new int[20]; // I can't change the pointer,
    *(obj->val1) = 20; // But I can change the memory it points to...
}

int main(int argc, char* argv[])
{
    // I need to be able to set foo and pass its value in as const into a function
    foo stoben;
    stoben.val1 = new int;
    *(stoben.val1) = 0;
    std::cout << *(stoben.val1) << std::endl; // Output is "0"
    fn( &stoben );
    std::cout << *(stoben.val1) << std::endl; // Output is "20"
    delete stoben.val1;
    return 0;
}

The code here is pretty self explanitory. I need to be able to make a non-const object and fill it with data, but then pass it to a function where this data cannot be modified. How can I go about this?

I know I can just pass in a const int pointer, but theoretically, this class contains several other pointers which I will need in "fn" as well.

Thanks,

Griff

like image 692
Griffin Avatar asked Jul 04 '10 23:07

Griffin


1 Answers

Since you tagged as C++, you could make the member private and make an accessor that returns a const int *. You could originally set the member via your constructor or a friend function.

like image 131
Brian R. Bondy Avatar answered Oct 26 '22 06:10

Brian R. Bondy