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的更多相关文章

  1. function overloading/ declare function

    Declare a function To declare a function without identifying the argument list, you can do it in thi ...

  2. Function overloading and return type

    In C++ and Java, functions can not be overloaded if they differ only in the return type. For example ...

  3. Function Overloading in C++

    In C++, following function declarations cannot be overloaded. (1)Function declarations that differ o ...

  4. [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 ...

  5. [c++] Operator overloading

    c++的操蛋属性:自己为一档,空一档,其他随意. UB_stack a; UB_stack b = a; // copy auto c = a; auto d {a}; // (or auto d = ...

  6. const成员函数

    尽管函数名和参数列表都相同,void foo( ) const成员函数是可以与void foo( )并存的,可以形成重载! 我们假设调用语句为obj.foo(),如果obj为non-const对象,则 ...

  7. C: const and static keywords

    原文:http://www.noxeos.com/2011/07/29/c-const-static-keywords/ C: const and static keywords Ok, once a ...

  8. const, static and readonly

    const, static and readonly http://tutorials.csharp-online.net/const,_static_and_readonly Within a cl ...

  9. [ES6] 22. Const

    'const' keyword is for creating a read only variable, something you can never change once created. ' ...

随机推荐

  1. Spring Cloud 生产环境性能优化

    先思考几个问题: 什么是百万并发连接? 什么是吞吐量? 操作系统能否支持百万连接? 操作系统维持百万连接需要多少内存? 应用程序维持百万连接需要多少内存? 百万连接的吞吐量是否超过了网络限制? 百万的 ...

  2. vue项目部署到docker中

    通过nginx镜像部署 vue项目npm run build打包成dist目录,有的打包会加上版本号 启动 docker 将dist目录通过xftp拷贝到linux服务器上,同目录下新建Dockerf ...

  3. 关于Thread的interrupt

    关于Thread的interrupt Thread的interrupt方法会引发线程中断. 主要有以下几个作用: 如Object的wait方法,Thread的sleep等等这些能够抛出Interrup ...

  4. 跟着老猫来搞GO-容器(1)

    前期回顾 前面的一章主要和大家分享了GO语言的函数的定义,以及GO语言中的指针的简单用法,那么本章,老猫就和大家一起来学习一下GO语言中的容器. 数组 数组的定义 说到容器,大家有编程经验的肯定第一个 ...

  5. 大爽Python入门教程 1-2 数与字符串

    大爽Python入门公开课教案 点击查看教程总目录 1 整数与浮点数 整数大家都知道,比如1, 2, 10, 123, 都是整数int. 浮点数是什么呢? 上一节的除法运算,不知道有没有人注意到,其结 ...

  6. Swift-技巧(五)设置圆角的代码

    摘要 实现控件圆角的代码时,会不假思索的写 cornerRadius 和 masksToBounds,因为搜索得到的设置圆角的代码就是这样.今天突发奇想,为什么要写 masksToBounds? 打个 ...

  7. 【开源库推荐】#3 Android EventBus的使用

    原文地址:[开源库推荐]#3 Android EventBus的使用 | Stars-One的杂货小窝 EventBus的Github Event bus for Android and Java t ...

  8. Python 爬取 豆瓣

    ... import urllib.request import time from bs4 import BeautifulSoup def url_open(url): response = ur ...

  9. [cf1396E]Distance Matching

    根据$dis(x,y)=d[x]+d[y]-2d[lca(x,y)]$,由于所有点都出现了1次,距离即$\sum_{i=1}^{n}d_{i}-2\sum d[lca(x,y)]$(以下假设根深度为0 ...

  10. P6585 中子衰变

    我们偶数的时候只要对称操作. 奇数的话,我们定义\(1\)的相反数为\(-1\),\(0\)相反数为\(0\). 我们维护最长的两边的相反串,中间一段除了一个端点,其他均被染成同色. 那么如果对方染端 ...