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. ' ...
随机推荐
- 一款吊炸天的AI图片增强工具!
背景 如果你工作中需要制作文档,PPT,或者给文章配图,或者需要制作视频.一定会有在网上寻找图片素材的经历. 但网上的图质量参差不一,有时候找到了喜欢的图,但是质量不行,分辨率太低. 有的人就忍了,但 ...
- 面霸篇:Java 集合容器大满贯(卷二)
面霸篇,从面试角度作为切入点提升大家的 Java 内功,所谓根基不牢,地动山摇. 码哥在 <Redis 系列>的开篇 Redis 为什么这么快中说过:学习一个技术,通常只接触了零散的技术点 ...
- Java设计模式之(四)——原型模式
1.什么是原型模式 Specify the kinds of objects to create using a prototypical instance,and create new object ...
- [loj2978]杜老师
假设所有素数从小到大依次为$p_{1},p_{2},...,p_{k}$,我们将$x$转换为一个$k$位的二进制数,其中从低到高第$i$位为1当且仅当其$p_{i}$的幂次为奇数 不难发现以下两个性质 ...
- [luogu5162]WD与积木
设$g_{n}$表示$n$个积木放的方案数,枚举最后一层所放的积木,则有$g_{n}=\sum_{i=1}^{n}c(n,i)g_{n-i}$(因为积木有编号的所以要选出$i$个) 将组合数展开并化简 ...
- [loj2136]地震后的幻想乡
考虑kruskal的过程:对$n$条边随机排列(排序),令$k$表示前$k$条边恰好能使图联通,根据题目的提示,即$E(\frac{k}{m+1})=\frac{E(k)}{m+1}$ 设$p(k)$ ...
- 【Java面试】-- 杂题
杂题 2019-11-03 21:09:37 by冲冲 1.类加载器的双亲委派机制 类加载器:把类通过类加载器加载到JVM中,然后转换成class对象(通过类的全路径来找到这个类). 双亲委派机制 ...
- 从ApacheTomcat架构谈面试到源码编译环境v10.0.12
概述 开启博客分享已近三个月,感谢所有花时间精力和小编一路学习和成长的伙伴们,有你们的支持,我们继续再接再厉 **本人博客网站 **IT小神 www.itxiaoshen.com 定义 Tomcat官 ...
- 职场工作方法论:目标管理SMART原则
目标管理由管理学大师彼得·德鲁克在他的著作<管理实践>(The Practice of Management)一书中提出.SMART原则(Specific具体的, Measurable可衡 ...
- Codeforces 1542E2 - Abnormal Permutation Pairs (hard version)(DP)
upd on 2021.7.7:修了个 typo Codeforces 题目传送门 & 洛谷题目传送门 首先考虑怎样处理"字典序小"这个问题,按照字典序比大小的套路,我们可 ...