Function overloading and const keyword
Predict the output of following C++ program.
1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 protected:
7 int x;
8 public:
9 Test (int i):x(i)
10 {
11 }
12
13 void fun() const
14 {
15 cout << "fun() const called " << endl;
16 }
17 void fun()
18 {
19 cout << "fun() called " << endl;
20 }
21 };
22
23 int main()
24 {
25 Test t1 (10);
26 const Test t2 (20);
27 t1.fun();
28 t2.fun();
29 return 0;
30 }
Output: The above program compiles and runs fine, and produces following output.
fun() called
fun() const called
The two methods ‘void fun() const’ and ‘void fun()’ have same signature except that one is const and other is not. Also, if we take a closer look at the output, we observe that, ‘const void fun()’ is called on const object and ‘void fun()’ is called on non-const object.
C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer. See this for more details.
What about parameters?
Rules related to const parameters are interesting. Let us first take a look at following two examples. The program 1 fails in compilation, but program 2 compiles and runs fine.
1 // PROGRAM 1 (Fails in compilation)
2 #include<iostream>
3 using namespace std;
4
5 void fun(const int i)
6 {
7 cout << "fun(const int) called ";
8 }
9 void fun(int i)
10 {
11 cout << "fun(int ) called " ;
12 }
13 int main()
14 {
15 const int i = 10;
16 fun(i);
17 return 0;
18 }
Output:
Compiler Error: redefinition of 'void fun(int)'
1 // PROGRAM 2 (Compiles and runs fine)
2 #include<iostream>
3 using namespace std;
4
5 void fun(char *a)
6 {
7 cout << "non-const fun() " << a;
8 }
9
10 void fun(const char *a)
11 {
12 cout << "const fun() " << a;
13 }
14
15 int main()
16 {
17 const char *ptr = "GeeksforGeeks";
18 fun(ptr);
19 return 0;
20 }
Output:
const fun() GeeksforGeeks
C++ allows functions to be overloaded on the basis of const-ness of parameters only if the const parameter is a reference or a pointer.
That is why the program 1 failed in compilation, but the program 2 worked fine. This rule actually makes sense. In program 1, the parameter ‘i’ is passed by value, so ‘i’ in fun() is a copy of ‘i’ in main(). Hence fun() cannot modify ‘i’ of main(). Therefore, it doesn’t matter whether ‘i’ is received as a const parameter or normal parameter. When we pass by reference or pointer, we can modify the value referred or pointed, so we can have two versions of a function, one which can modify the referred or pointed value, other which can not.
As an exercise, predict the output of following program.
1 #include<iostream>
2 using namespace std;
3
4 void fun(const int &i)
5 {
6 cout << "fun(const int &) called ";
7 }
8 void fun(int &i)
9 {
10 cout << "fun(int &) called " ;
11 }
12 int main()
13 {
14 const int i = 10;
15 fun(i);
16 return 0;
17 }
Output:
fun(const int &) called
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-25 22:33:28
Function overloading and const keyword的更多相关文章
- function overloading/ declare function
Declare a function To declare a function without identifying the argument list, you can do it in thi ...
- Function overloading and return type
In C++ and Java, functions can not be overloaded if they differ only in the return type. For example ...
- Function Overloading in C++
In C++, following function declarations cannot be overloaded. (1)Function declarations that differ o ...
- [Javascript] Understand common misconceptions about ES6's const keyword
Values assigned with let and const are seen everywhere in JavaScript. It's become common to hear the ...
- [c++] Operator overloading
c++的操蛋属性:自己为一档,空一档,其他随意. UB_stack a; UB_stack b = a; // copy auto c = a; auto d {a}; // (or auto d = ...
- const成员函数
尽管函数名和参数列表都相同,void foo( ) const成员函数是可以与void foo( )并存的,可以形成重载! 我们假设调用语句为obj.foo(),如果obj为non-const对象,则 ...
- C: const and static keywords
原文:http://www.noxeos.com/2011/07/29/c-const-static-keywords/ C: const and static keywords Ok, once a ...
- const, static and readonly
const, static and readonly http://tutorials.csharp-online.net/const,_static_and_readonly Within a cl ...
- [ES6] 22. Const
'const' keyword is for creating a read only variable, something you can never change once created. ' ...
随机推荐
- 一维前缀和 连续数组和为k
给定一个整数数组和一个整数 k ,请找到该数组中和为 k 的连续子数组的个数. 滑动窗口没办法解决有负数的情况 方法一: 预处理 前缀和 sum_ij = preSum[j] - preSum[i-1 ...
- Linux常用命令和快捷键整理:(2)常用快捷键
前言: Linux常用快捷键和基本命令整理,先上思维导图: linux常用命令请见:https://www.cnblogs.com/yinzuopu/p/15516499.html 基本快捷键的使用 ...
- celery ValueError: invalid literal for int() with base 10: '26379;sentinel'
celery使用redis sentinel作为broker的时候,因为redis sentinel配置字符串格式解析报错 ValueError: invalid literal for int() ...
- 暑假算法练习Day3
第三天!!!最近要开始归纳总结Python学习啦!! 1006 换个格式输出整数 (15 分) 让我们用字母 B 来表示"百".字母 S 表示"十",用 12. ...
- Mac下Shell脚本使用学习笔记(一)
参考文献 Shell 教程 MAC常用终端命令行 Mac下Shell脚本使用 1.使用终端创建test.sh: (1)进入指定文件夹路径(命令示例:cd Desktop/面向对象程序设计): (2)创 ...
- UE4中C++编程(一)
一: C++工程和Gameplay框架 GameInstance 它适合放置独立于关卡的信息,比如说显示UI. GameMode 表示游戏玩法, 包含游戏进行的规则和胜利条件等等信息,游戏模式是和关卡 ...
- Centos8 Docker部署 .Net6 项目
.Net6项目发布 1.在VS中发布项目,并编写好Dockerfile文件 Dockerfile文件内容如下: FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS ...
- C/C++ Qt TableDelegate 自定义代理组件
TableDelegate 自定义代理组件的主要作用是对原有表格进行调整,例如默认情况下Table中的缺省代理就是一个编辑框,我们只能够在编辑框内输入数据,而有时我们想选择数据而不是输入,此时就需要重 ...
- [GZOI2017]配对统计
发现我们可以在\(O(n)\)里很多处理出至多\(2n\)对好对. 然后转化成二维偏序. 然后想怎么做怎么做:排序+BIT,莫队都行.
- python3 excel读、写、修改操作
python3上Excel文件操作的库比较多,新手一开始不知道如何选择合适的库,故整理如下: xlwt: 只能写不能读,只支持python2.3到python2.7版本,只支持xls文件. xlrd ...