Difficulty Level: Rookie

  Predict the output of below C++ programs.

Question 1

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 int value;
7 public:
8 Test(int v);
9 };
10
11 Test::Test(int v)
12 {
13 value = v;
14 }
15
16 int main()
17 {
18 Test t[100];
19 return 0;
20 }

  Output: Compiler error

  The class Test has one user defined constructor “Test(int v)” that expects one argument. It doesn’t have a constructor without any argument as the compiler doesn’t create the default constructor if user defines a constructor (See this).

  Following modified program works without any error.

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 int value;
7 public:
8 Test(int v = 0);
9 };
10
11 Test::Test(int v)
12 {
13 value = v;
14 }
15
16 int main()
17 {
18 Test t[100];
19 return 0;
20 }

Question 2

 1 #include<iostream>
2 using namespace std;
3 int &fun()
4 {
5 static int a = 10;
6 return a;
7 }
8
9 int main()
10 {
11 int &y = fun();
12 y = y +30;
13 cout << fun();
14 return 0;
15 }

  Output: 40
  The program works fine because ‘a’ is static. Since ‘a’ is static, memory location of it remains valid even after fun() returns. So a reference to static variable can be returned.

Question 3

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 public:
7 Test();
8 };
9
10 Test::Test()
11 {
12 cout<<"Constructor Called \n";
13 }
14
15 int main()
16 {
17 cout<<"Start \n";
18 Test t1();
19 cout<<"End \n";
20 return 0;
21 }

  Output:
  Start
  End

  Note that the line “Test t1();” is not a constructor call. Compiler considers this line as declaration of function t1 that doesn’t recieve any parameter and returns object of type Test.

  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-27  15:23:22

  

最新文章

  1. maven 快照
  2. wireshake抓包,飞秋发送信息,python
  3. Java 代码编译和执行的整个过程
  4. DFS Codeforces Round #290 (Div. 2) B. Fox And Two Dots
  5. Snmp配置
  6. yii学习小结
  7. 关于sublime text
  8. selenium文件上传的实现
  9. 如何使用NSFetchedResultsController-备
  10. 基于mAppWidget实现手绘地图--索引&amp;DEMO
  11. python手记(46)
  12. iframe 高度自适应
  13. Python神器 Jupyter Notebook
  14. supervisor进程管理的使用
  15. win10 再次重装系统
  16. Python基础-python数据类型之元祖、字典(四)
  17. python 使用多进程实现并发编程/使用queue进行进程间数据交换
  18. node.js 在使用child_process 模块时候,调试端口占用的问题解决方案(EADDRINUSE)
  19. [ GIT ] GIT tip : A simple .gitconfig file
  20. sendmsg/recvmsg和struct msghdr

热门文章

  1. 测试平台系列(72) 了解ApScheduler基本用法
  2. connect & send 在三次握手过程中的有趣问题
  3. jacoco-统计代码覆盖率并生成报告
  4. 移动GPU分类/百科
  5. 【linux系统】命令学习(七)进阶命令 curl jq
  6. [atAGC047F]Rooks
  7. 【JavaSE】格式化输出
  8. layui增加转圈效果
  9. C/C++ Qt 给ListWidget增加右键菜单
  10. Codeforces 643G - Choosing Ads(线段树)