
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Function Overloading and Const Keyword in C++
In C++, we can overload functions. Some functions are normal functions; some are constant type functions. Let us see one program and its output to get the idea about the constant functions and normal functions.
Example
#include <iostream> using namespace std; class my_class { public: void my_func() const { cout << "Calling the constant function" << endl; } void my_func() { cout << "Calling the normal function" << endl; } }; int main() { my_class obj; const my_class obj_c; obj.my_func(); obj_c.my_func(); }
Output
Calling the normal function Calling the constant function
Here we can see that the normal function is called when the object is normal. When the object is constant, then the constant functions are called.
If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error.
Example
#include <iostream> using namespace std; class my_class { public: void my_func(const int x) { cout << "Calling the function with constant x" << endl; } void my_func(int x){ cout << "Calling the function with x" << endl; } }; int main() { my_class obj; obj.my_func(10); }
Output
[Error] 'void my_class::my_func(int)' cannot be overloaded [Error] with 'void my_class::my_func(int)'
But if the arguments are reference or pointer type, then it will not generate error.
Example
#include <iostream> using namespace std; class my_class { public: void my_func(const int *x) { cout << "Calling the function with constant x" << endl; } void my_func(int *x) { cout << "Calling the function with x" << endl; } }; int main() { my_class obj; int x = 10; obj.my_func(&x); }
Output
Calling the function with x
Advertisements