j4x
j4x

Reputation: 3716

Constructor for `const` object

Consider this code:

#include <iostream>

class test
{
public:
    test( char *arg )
    :   _arg( arg )
    {}  
    char *_arg;
};

int main( )
{
    char *txt1       = "Text one";  // Ignore this warning.
    const char *txt2 = "Text two";

    test       t1( txt1 );  // Normal case, nothing new.
    const test t2( txt2 );  // Since object is const, I'd like to be able to pass a const argument in.
}

It blows up with the error:

error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
   const test t2( txt2 );

Then I tried to add a second constructor to test whether the compiler could select the right one for t2, my const object:

    test( const char *arg )
    :   _arg( arg )
    {}  

but then the error is:

error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
  : _arg( arg )

So declaring my object as const does not make its fields const as well.

How to properly declare my class constructors so that it can handle const and non-const object creation?

Upvotes: 5

Views: 5509

Answers (7)

Quential33
Quential33

Reputation: 181

Interesting. Look at the example below (object myclass2) to learn how a const object does not necessarily provide the protection that you need!

#include <iostream>
#include <cctype>
#include <cassert>

class MyClass
{
  public:
    MyClass(char * str1, size_t size1) : str{str1}, size{size1}
    {
    }
    char * capitalizeFirstChar()
    {
        *str = std::toupper(*str);
        return str;
    }
    char nthChar(size_t n) const
    {
        assert(n < size);
        return str[n];
    }

    char * str;
    size_t size;
};


int main()
{
    {
        static char str1[] = "abc";
        MyClass myclass1(str1, sizeof(str1) / sizeof(*str1));

        myclass1.capitalizeFirstChar();
        std::cout << myclass1.nthChar(0) << std::endl;
    }
    std::cout << "----------------------" << std::endl;
    {
        static const char str2[] = "abc";
        //             UGLY!!! const_cast
        const MyClass myclass2(const_cast<char *>(str2), sizeof(str2) / sizeof(*str2));

        // myclass2.capitalizeFirstChar();        // commented: will not compile

        std::cout << myclass2.nthChar(0) << std::endl;

        char c = 'x';
        // myclass2.str = &c;                     // commented: will not compile
                                                  // The const myclass2, does not
                                                  // allow modification of it's members

        myclass2.str[0] = 'Z';  // WILL COMPILE (!!) and should cause a segfault
                                // The const myclass2, CANNOT PROTECT THE OBJECT POINTED TO by str
                                // Reason: the member in MyClass is 
                                //                      char *str  
                                //         not 
                                //                const char *str

        std::cout << myclass2.nthChar(0) << std::endl;
    }
}

Ok, the str member issue is actually best solved, by just making the members private.

But what about that ugly const_cast? One way of solving this is splitting into a Const baseclass, and deriving for non-const behaviour (working with const-casts). Like this perhaps:

#include <iostream>
#include <cctype>
#include <cassert>

class MyClassConst
{
  public:
    MyClassConst(const char * str1, size_t size1) : str{str1}, size{size1}
    {
    }
    char nthChar(size_t n) const
    {
        assert(n < size);
        return str[n];
    }

    const char * str;
    size_t size;
};

class MyClass : public MyClassConst
{
  public:
    MyClass(char * str1, size_t size1) : MyClassConst{const_cast<const char *>(str1), size1}
    {
    }
    char * capitalizeFirstChar()
    {
        char * cp = const_cast<char *>(str);
        *cp       = std::toupper(*cp);
        return cp;
    }
};


int main()
{
    {
        static char str1[] = "abc";
        MyClass myclass1(str1, sizeof(str1) / sizeof(*str1));
        myclass1.capitalizeFirstChar();
        std::cout << myclass1.nthChar(0) << std::endl;
    }
    std::cout << "----------------------" << std::endl;
    {
        static const char str2[] = "abc";
        //             NICE: no more const_cast
        const MyClassConst myclass2(str2, sizeof(str2) / sizeof(*str2));

        // a.capitalizeFirstChar();               // commented: will not compile

        std::cout << myclass2.nthChar(0) << std::endl;

        char c = 'x';
        // myclass2.str = &c;                     // commented: will not compile
                                                  // The const myclass2, does not
                                                  // allow modification of it's members

        // myclass2.str[0] = 'Z';                 // commented: will not compile

        std::cout << myclass2.nthChar(0) << std::endl;
    }
}

Is it worth it? Depends. One is kindof trading the const-cast outside of the class... for const-cast inside the class. So maby for library code (including ugly internals, and static code analysis exceptions), with clean outside usage, it's a match...

Upvotes: 0

Amir Kirsh
Amir Kirsh

Reputation: 13852

A note: this is a long answer for a use case that might be a bad design. Yet, the reason and the main focus for the long answer is:

  • to show and explain what is not possible
  • to present a way in which one can make the compiler decide based on the constness of a parameter whether to create a holding const object and to preserve this information even if the object is passed on. Which is very close to the OP request.

As explained in other answers, you can have two constructors, one for const parameter and the other for non-const, but both constructors would just create an object that can be either const or non-const. So this doesn't help.

Another approach could be to have a factory method that would create either a const object or a non-const, according to the constness of the parameter. Though this may sound promising it would not allow to preserve the semantics of the difference between the two, as shown in the following pseudo code:

// creating an object holding a const, using the factory method `create`:
const MyClass const_holder  = create(const_param);

// however you cannot prevent this:
MyClass non_const_holder = create(const_param);

The factory would create in the second case above a const object that would be copied or moved (or just created directly as non_const_obj with copy elision, since C++17 as mandatory copy elision). You cannot do anything to avoid the second case unless you delete copy and move, in which case the first case wouldn't work also and the all thing collapses.

So, without creating actually two different types it is impossible to preserve the information of which constructor was used and to avoid assignment of an object created with const param into an object that doesn't.

However, there is no real need to bother the user with the fact that there are two classes, with a proper template implementation the user can have simple code that gives the feeling that there is only one class in the game, something like:

// creating a const holder with a factory method
// the type would *remember* that it is holding a const resource
// and can act accordingly
auto const_holder = create(const_param);

// and you can also create a non const holder with the same factory
auto non_const_holder = create(param);

These operations would be allowed:

// (a) calling a non const method on the content of the non const holder
non_const_holder->non_const_method();

// (b) assigning a non const holder into a const holder object
//     -- same as assigning char* to const char*
const_holder = non_const_holder;

These operations would NOT be allowed:

// (a) calling a non const method on the content of a const holder
const_holder->non_const_method(); // should be compilation error

// (b) assigning a const holder into a non const holder object
//     -- same as one cannot assign const char* to char*
non_const_holder = const_holder; // should be compilation error

In a way, this is very similar to the idea of propagate_const...

The code would have a factory method:

template<class T>
Pointer<T> create(T* t) {
    return Pointer<T>::create(t);
}

And two implementations for the template class Pointer.

base template:

template<class T>
class Pointer {
    T* ptr;
    Pointer(T* p) : ptr(p) {}
    friend class Pointer<const T>;
public:
    // factory method
    static Pointer create(T* p) {
        return p;
    }
    operator T*() { return ptr; }
    operator const T*() const { return ptr; }
};

and a specialized one for the const version:

template<class T>
class Pointer<const T> {
    const T* ptr;
    Pointer(const T* p) : ptr(p) {}
public:
    Pointer(const Pointer<T>& other) {
        ptr = other.ptr;
    }
    // factory method
    static const Pointer create(const T* p) {
        return p; 
    }
    operator const T*() { return ptr; }
    operator const T*() const { return ptr; }
};

The main would look like:

int main() {
    char str[] = "hello";
    const char* const_str = "hello";
    // non-const - good!
    auto s1 = create(str);
    // const holding non-const - ok!
    const auto s2 = create(str);
    // non-const that holds const - good!
    auto s3 = create(const_str);
    // also possible: const holding const
    const auto s4 = create(const_str);

    s1[4] = '!'; // OK
    // s2[0] = '#'; // obviously doesn't compile - s2 is const
    // s3[0] = '@'; // doesn't compile - which is good - s3 holds const!
    // s4[0] = 'E'; // obviously doesn't compile - s4 is const
    // avoids assignment of s3 that holds a const into s1 that holds a non-const
    // s1 = s3; // <= doesn't compile - good!
    s3 = s1; // allows assignment of `holding-non-const` into `holding-const`
    s3 = s2; // allows assignment of `holding-non-const` into `holding-const`
    s3 = s4; // allows assignment of `holding-const` into `holding-const`
}

Code: http://coliru.stacked-crooked.com/a/4729be904215e4b2

Upvotes: 4

luk32
luk32

Reputation: 16090

The problem you experience goes a bit deeper. It's an indication of a design issue.

You would like to expose only part of the API. You say that for a const object you will call only const methods and for non-const you can do anything. But this is problematic.

Either you accept const object strip it from const qualifier, and won't call non-const methods by a silent contract. Or, you need to limit methods, which makes a different object - type-wise.

C# library does it by providing a limited interface which wraps around original object and exposes only const methods. Something like this:

#include <iostream>
using namespace std;

struct A {
    void f1() const {cout << "foo\n"; }
    void f2() {cout << "bar\n"; }
};

struct readonlyA {
    readonlyA(const A& a) : _a(a) {};
    void f1() const {_a.f1();};
private:
    const A& _a;
};

int main() {
    A a;
    readonlyA roA(a);
    a.f2();
    roA.f1();
    roA.f2(); // error
    return 0;
}

It's basically a read-only proxy.

Upvotes: 2

Useless
Useless

Reputation: 67852

How to properly declare my class constructors so that it can handle const and non-const object creation?

The object isn't const during construction, or the constructor wouldn't be able to initialize the object (since all data members would be const).

So, constructors can't be const-qualified and you can't have a constructor overload used for const objects.

Now, you can overload on the argument, but your data member always has type char * during construction, although it's qualified to char * const (not const char *) when used in a const-qualified instance of test.

Options are:

  1. overload constructor on argument type, and store a char * always. If you're passed a const char * you have to copy it (and you're responsible for knowing that you own and must deallocate this memory)

    In this scheme, you rely on keeping the pointer private and using const-qualified accessors to stop the contents of the pointer being changed via a const-qualified object.

    Again, you need to do this manually because char * const is a different type than const char *, because constness of the pointed-to type isn't related to constness of the pointer: having a const instance of your class just stops you mutating the pointer, not the characters it points to.

  2. overload constructor and store a const char * always. This avoids copying but obviously doesn't work if you sometimes need to change the pointed-to characters

  3. just write different mutable-string and immutable-string classes

If it helps, consider this:

template <typename T> struct test {
    T* p_;
    test(T *p) : p_(p) {}
};
template <typename T> test<T> mktest(T *p) { return {p}; }

and note that

const char *ccp = "immutable characters in a string literal";
char *cp = strdup(ccp);
auto a = mktest(ccp);
auto b = mktest(cp);

gives a the type test<const char>, and b the type test<char> and that these types are not the same, are not convertible, and are no more closely related in the language than to test<T> for any other type T.

Upvotes: 5

Robert Watkins
Robert Watkins

Reputation: 26

The compiler is preventing you from carelessly discarding the constness...

    class test
    {
         public:
            test(const char *arg)
            : _arg(arg)
         {}
         const char *_arg;
    };

Upvotes: 0

ComicSansMS
ComicSansMS

Reputation: 54777

The compiler does not care about what you actually do with the object at runtime.

Const works because the compiler will forbid certain things at compile time that could potentially change the object. This might be over-restrictive in certain situations, as the compiler often does not have the full picture of what's going on in the program.

Take for example the invocation a non-const member function on a const object: Even if the member function does not actually change the object's state, the compiler will still forbid it because the non-const function could potentially change the object.

Similar in your example: Even though you don't change the member for that particular const instance of the class, there could be other non-const instances of the same class somewhere, which is why it will refuse construct any instance of the class from a const object.

If you want a class that is guaranteed to leave its members unchanged, that would be a different type:

class test
{
public:
    test( char *arg )
    :   _arg( arg )
    {}  
    char *_arg;
};

class immutable_test
{
public:
    immutable_test(char const* arg)
        :_arg(arg)
    {}

    char const* _arg;
};

int main( )
{
    char *txt1       = "Text one";  // Ignore this warning.
    const char *txt2 = "Text two";

    test           t1( txt1 );
    immutable_test t2( txt2 );
}

Upvotes: 1

patatahooligan
patatahooligan

Reputation: 3321

It can't be done. Just because the object is const, it doesn't mean that it guarantees the char* won't be used to modify its value. The constructor can mutate the argument, and code outside the class can modify its content if it is exposed. Consider the following example.

struct Test {
    char* buffer;

    Test(char* buffer):
        buffer(buffer)
    {
        buffer[0] = 'a';
    }

    char* get() const {
        return buffer;
    }
};

int main(int argc, char* argv[]) {
    std::string s{ "sample text" };

    const Test t(s.data());

    t.get()[1] = 'b';
    t.buffer[2] = 'c';

    std::cout << s << '\n';
}

The above prints abcple text, even though t is const. Even though it never modifies its members, it does change the pointed-to string and it allows outside code to modify it, too. This is why const objects cannot accept const char* arguments to initialize their char* members.

Upvotes: 0

Related Questions