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. 一文搞懂js中的typeof用法

    基础 typeof 运算符是 javascript 的基础知识点,尽管它存在一定的局限性(见下文),但在前端js的实际编码过程中,仍然是使用比较多的类型判断方式. 因此,掌握该运算符的特点,对于写出好 ...

  2. JavaScript 简单介绍

    一.简介 JavaScript是一门面向对象的动态语言,他一般用来处理以下任务: 修饰网页 生成HTML和CSS 生成动态HTML内容 生成一些特效 提供用户交互接口 生成用户交互组件 验证用户输入 ...

  3. Mysql教程:(四)连接查询

    连接查询 1.左连接查询: mysql> select stu.*,sc.*,maths+sc.chinese+sc.english from student stu left join sco ...

  4. CSS 海盗船加载特效

    CSS 海盗船加载特效 <!DOCTYPE html> <html lang="en"> <head> <meta charset=

  5. hivesql笔记

    一.常用聚合函数 count():计数 count(distinct 字段) 去重统计 sum():求合 avg():平均 max():最大值 min():最小值 二.hivesql执行顺序 from ...

  6. vue中this.$set的用法

    之前了解这个方法的时候,感觉这一辈子也用不到这个方法,因为当时没有应用场景,但是还真有用的时候,我相信你们也有用到时候. 从三个方面给大家说一下这个this.$set: 1.this.$set实现什么 ...

  7. [bzoj1037]生日聚会

    dp,用f[i][j][x][y]表示i个男孩,j个女孩,以i+j为结尾的子序列男-女最多为x,女-男最多为y的合法方案数,转移到f[i+1][j][x+1][max(y-1,0)]和f[i][j+1 ...

  8. html+css第六篇-定位

    relative相对定位/定位偏移量 position:relative; 相对定位 a.不影响元素本身的特性: b.不使元素脱离文档流: c.如果没有定位偏移量,对元素本身没有任何影响: 定位元素位 ...

  9. 最难忘的一次bug:谢谢实习时候爱学习的自己

    前言 时间的车轮一直向前不停,试图在时光洪流中碾碎一些久远的记忆.虽然记忆中的人离我越来越远,但是故事却越来越深刻. 当在博客园看到这次的正文题目是"最难忘的bug",脑海里瞬间浮 ...

  10. Codeforces Gym 101221G Metal Processing Plant(2-SAT)

    题目链接 题意:有 \(n\) 个元素,第 \(i\) 个数与第 \(j\) 个数之间有一个权值 \(d_{i,j}\),\(d(i,j)=d(j,i)\). 定义函数 \(D(S)=\max\lim ...