What is the difference between writing const before and after the function prototype?
Printable View
What is the difference between writing const before and after the function prototype?
You need to ask your questions more clearly. Your question is meaningless. A "function definition" has a specific meaning in C++, which I suspect you have misunderstood. Within that meaning, const before or after the function definition either equates to "code that will not compile" or "the const has no relationship to the function definition".
If you have a particular meaning in mind of "before the function definition" and "after the function definition" you need to provide examples so we understand what you mean.
sorry its function prototype.
I have changed it.
What part ofdo you fail to understand?Quote:
you need to provide examples so we understand what you mean.
I think he means something like this, two different member functions:
The difference is that "someFunc" returns a const reference to a string and someOtherFunc returns a non-const reference to a string. Another difference is that "someOtherFunc" doesn't let you modify the object for which this function is a member, and that "someFunc" can not be called on a const object.Code:class A {
public:
const std::string &someFunc();
std::string &someOtherFunc() const;
};
So: const after the function declaration means that it is possible to call the function when the object is const, though it makes sure you never change the object, at least not whatever you aren't allowed to change.
For instance:
So whenever you make a function that doesn't change the object, you should always make it const. That is completely unrelated to a const returned value, the following is perfectly legal and very common:Code:A a;
const A aConst;
a.someFunc(); // Legal: call on non-const object to a function that doesn't take a const object.
a.someOtherFunc(); // Legal: const function called on non-const object; this object will become const in someOtherFunc.
aConst.someFunc(); // Illegal: someFunc() requires a non-const object, but a const object was passed.
aConst.someOtherFunc(); // Legal: aConst is a const object, so it's fine to call a function making it const.
Code:const std::string &someFunction() const;