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