Archived

This topic is now archived and is closed to further replies.

GekkoCube

returning a const * verses a non-const *.

Recommended Posts

GekkoCube    116
I noticed that returning a const * and using it to call a function of that type...for example:

// method

const CPerson* GetPersonPtr()
{
  return m_pPerson;
}

// using the method somewhere

CPerson *pPerson = GetPersonPtr();

// try to use CPerson''s function

pPerson->GetName(); // error!!

First of all, why is this? pPerson is a const * CPerson, meaning the data it points to is constant. Should GetPersonPtr() be a const? ie: const CPerson* GetPersonPtr() const;

Share this post


Link to post
Share on other sites
Thrump    169
When you return a const, you''re telling the compiler and other programmers that that data shouldn''t be modified.

The compiler will then prevent you from changing that data, by giving you errors.

In your example, pPerson and GetName must both be const as well, otherwise you could modify what you said was const.

Share this post


Link to post
Share on other sites
gimp    142
Yep, specifically, if you want to hand out const pointers to object then you are making a decision to ''never change the object''. That said if you call a function in an object that is no specifically marked as const the compiler will help you out in remembering that your about to do something you didn''t intend on doing.

All my Get* accessors are marked as const. Example:


void SetName(const std::string& a_Name);
const std::string& GetName(void) const;


see how the Set is not protected. It is still valid to have a const object pointer if you never intend on calling a non const function from that pointer though. So in my case I can happily do this:


const CUser* NewUser = (const CUser*)Array;
cout << NewUser->GetName()


and the compiler doesn''t find any flaws in what I''m doing. If I cal the SetName function however it''ll flag me an error. A const pointer is used to define HOW a pointer may be used.


Share this post


Link to post
Share on other sites