Jump to content
  • Advertisement


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


returning a const * verses a non-const *.

This topic is 5141 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!