1

This code compiled.

struct A
{
    const int *getX() const
        {
            return &x;
        }

    int *getX()
        {
            const A *thisConst = this;
            return const_cast<int *>(thisConst->getX());
        }


    void f()
        {
            int *p = getX();
        }

    int x;
};

But this code didn't.

struct I
{
    virtual const int *getX() const = 0;

    int *getX()
        {
            const I *thisConst = this;
            return const_cast<int *>(thisConst->getX());
        }
};

struct A : I
{
    virtual const int *getX() const
        {
            return &x;
        }

    void f()
        {
            int *p = getX();
        }

    int x;
};

'const_cast' : cannot convert from 'const int *' to 'int *'

I know that if I will give different names it will be compiled. But are there ways without functions renaming?

2
  • Your title doesn't seem to be asking the same thing as your question... could you change one of the two to avoid confusion? Also, what exactly are you trying to achieve here? Commented Jun 26, 2015 at 0:59
  • I want to compile this code without getX renaming. Commented Jun 26, 2015 at 1:03

1 Answer 1

1

'const_cast' : cannot convert from 'const A *' to 'int *'

I didn't get this error while trying to compile your program, instead I got

error: invalid conversion from 'const int*' to 'int*' [-fpermissive]

To compile successfully I corrected following line

int *p = getX();

to

const  int *p = getX(); 

const int * and int* are two different types, you can't assign it directly without cast or modify the type of the variable p.

Sign up to request clarification or add additional context in comments.

3 Comments

I made some edits. I know difference between const T * and T *. But I need to be able to get T * because object which I replaced by int in this question calls not const method.
@Ufx if you edit do it as additional explanation instead changing the posted question. I don't know what you have edited.
See an example for editing question here : stackoverflow.com/questions/31063331/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.