Sign in to follow this  

[C++] Why return const to value?

This topic is 3295 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

Let's say we have something like this:
class MyClass
{
private:
	char name[50];

public:
	char * getName()
	{
		return name;
	}
};
The above code is unsafe because it is easy to get the pointer to name and change it outside the class. The solution is to make some modification:
	const char * getName()
	{
		return name;
	}
But I don't understand why there appears const modifier when the returning value is not a pointer (I've seen many people doing so). For example:
const CVector3 operator + (const CVector3 &v1, const CVector3 &v2)
What does const affect in the above function?

Share this post


Link to post
Share on other sites
It's not unsafe as such, but it takes away control from the class.


class MyString
{
char* buffer;
unsigned length;
public:
char* str() { return buffer; }
};



Now you've given the user the ability to modify the string (make it shorter or add characters) but the class wouldn't know that and wouldn't be able to modify the length value accordingly.

If a class is responsible for maintaining certain conditions (e.g that buffer[length] always equals '\0'), then you just can't give users write access to internal implementation details.

Returning a const char* is fine though, since the user can use the result for look-up but can't change the buffer.

Quote:

const CVector3 operator + (const CVector3 &v1, const CVector3 &v2)


This is to disallow code like

CVector3 a, b, c;
a + b = c;


With const assigning to the temporary returned from a + b results in a compiler error, instead of compiling and perhaps not doing what was intended.

Share this post


Link to post
Share on other sites
I knew about const char * ;)
Quote:

But I don't understand why there appears const modifier when the returning value is not a pointer


The only dilema I had was about this const CVector3. Now I know what it is for - thanks for explanation.

Share this post


Link to post
Share on other sites

This topic is 3295 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this