I am not sure whether I am missing something basic. But I am unable to understand why the compiler is generating the error for this code:
class A { }; class B { public: B(); A* get() const; private: A* m_p; }; B::B() { m_p = new A; } A* B::get() const { //This is compiling fine return m_p; } class C { public: A* get() const; private: A m_a; }; A* C::get() const { //Compiler generates an error for this. Why? return &m_a; }
EDIT: The compiler error is : error C2440: ‘return’ : cannot convert from ‘const class A *’ to ‘class A *’ Conversion loses qualifiers
constin the function signature tells the compiler that the object’s members may not be modified. Yet you return a non-constpointer to a member, thus allowing a violation of that promise.In your class
B, you make/break no promise since you don’t return a pointer to a member, you return a copy of it (and the member happens to be a pointer).