0
Can you overload class methods with const and non-const? C++
For example, can I have 2 methods in 1 class with the same name, and return type, and number of arguments, but one is const and one isn't? So you can call the same method from both const objects of that class, and non-const objects of the same class. In other words - is this code valid? class SomeClass() { public: const string PrintFunction() {return "Hello";} string PrintFunction() {return "Hello";} }; Sorry if my question is unclever. Thanks in advanced!
4 Answers
+ 5
how will the compiler know which function he going to use ?
only a change of the parameters can used for overloading a function not the const keywords and not the type of return.
you must understand that the compiler that is a program should be able to understand in one and only one way your code, they musn't be any hesitations.
+ 5
No you cannot, the code isn't valid, you can try it on the playground (note that you should remove the parenthesis after the name of the class)
+ 3
1. The using const keyword with functions ensures that functions does not perform any modification accidental changes to object on which they are called.
It also guarantees it will not call any non-const member functions, as they may modify the object
2. When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects
Now about your query
Function overloading is usually used to enhance the readability of the program. When you have to perform one single operation with different number or types of arguments, then you overload a function. This can be done by
- By changing number of Arguments.
- By having different types of argument.
So, in light of above rules, your code is not valid.
0
Yes, you can. In some cases, you must do that. In your example, you must make a minor change as follows:
const string PrintFunction() const {return "Hello";}