views:

102

answers:

3

Hello! Code first:

struct Foo {
    char * DataPtr;
}; 

class ISomeInterface {
public:
    Foo GetFoo( ) const;
    Foo GetFoo( );
};

The Foo::DataPtr is a pointer to an internal buffer of the object behing ISomeInterface. Is there a way to make sure that the Foo::DataPtr returned by the const version of ISomeInterface::GetFoo is a const char * ?

+1  A: 

A struct

struct Foo {  
    char * DataPtr;  
}

is not the same as

struct Foo {  
    const char * DataPtr;
}

so you cannot differentiate how you would like.

You could make the const GetFoo() return a const Foo object (which I suspect is not what you want, as it will make all the member variables const), or make another struct with a const char * DataPtr (say FooConst) which is returned on the const call.

Rodion Ingles
Actually, I could use a const object, since it is just a data object that is supposed to be read-only. I was just not sure if I can use const on an object, or just on references and pointers.
Space_C0wb0y
+5  A: 

You need a

struct ConstFoo {
   const char* DataPtr;
};

for this. The const in C++ is not transitive. (this is also why you have iterator and const_iterator.)

KennyTM
So, no simple solution then. Thanks.
Space_C0wb0y
A: 

You could try to change the design of your Foo and 'hide' the acess to DataPtr behind functions. For instance:

class Foo {
    char * DataPtr;
public:
    //just some examples
    void doThis() const {}
    void doThat() {}
}; 

class ISomeInterface {
public:
    const Foo GetFoo( ) const { return Foo(); }
    Foo GetFoo( ) { return Foo(); }
}; 

...

const Foo foo1 = ISomeInterface().GetFoo();
foo1.doThis();
foo1.doThat(); //error
Foo foo2 = ISomeInterface().GetFoo();
foo2.doThis();
foo2.doThat();

Providing functions that define which operations are const and those that are not you can avoid duplicating your Foo and obtain the const-correctness restrictions you seem to be aiming for.

fogo
Thanks for the answer. I was hoping to get it working without that, to avoid unecessary code clutter.
Space_C0wb0y