J
Jens Thoms Toerring
Hi,
I am rather new to C++ and have run into a problem where I
haven't found an answer yet by searching (probably didn't find
the right search terms). I Have this simple program:
#include <iostream>
class A
{
public:
A( int i ) : m_ip( new int[ i ] ) { }
int const * ip( ) const { std::cout << "const\n"; return m_ip; }
int * ip( ) const { std::cerr << "non-const\n"; return m_ip; }
private:
int * m_ip;
};
int main( )
{
A a( 10 );
int const * ip = a.ip( );
std::cout << ip[ 2 ] << '\n';
}
My exectation was that when calling ip() to get a const pointer
the compiler would be able to figure out I want it to use the
first ip() method that returns a const pointer. But it turns out
that always the second one is invoked. I'm not sure why and if
there's a way that I can make it pick the second one (short of
using different names for the methods)? I also noticed the same
effect when using const versus non-const references as return
values, also there the non-const returning function is called
eben when one asks for a const reference. Does all this only
work when overloading the [] operator?
Best regards, Jens
I am rather new to C++ and have run into a problem where I
haven't found an answer yet by searching (probably didn't find
the right search terms). I Have this simple program:
#include <iostream>
class A
{
public:
A( int i ) : m_ip( new int[ i ] ) { }
int const * ip( ) const { std::cout << "const\n"; return m_ip; }
int * ip( ) const { std::cerr << "non-const\n"; return m_ip; }
private:
int * m_ip;
};
int main( )
{
A a( 10 );
int const * ip = a.ip( );
std::cout << ip[ 2 ] << '\n';
}
My exectation was that when calling ip() to get a const pointer
the compiler would be able to figure out I want it to use the
first ip() method that returns a const pointer. But it turns out
that always the second one is invoked. I'm not sure why and if
there's a way that I can make it pick the second one (short of
using different names for the methods)? I also noticed the same
effect when using const versus non-const references as return
values, also there the non-const returning function is called
eben when one asks for a const reference. Does all this only
work when overloading the [] operator?
Best regards, Jens