Output of C++ Program | Set 4
Difficulty Level: Rookie
Predict the output of below C++ programs.
Question 1
1 #include<iostream>
2 using namespace std;
3
4 int x = 10;
5 void fun()
6 {
7 int x = 2;
8 {
9 int x = 1;
10 cout << ::x << endl;
11 }
12 }
13
14 int main()
15 {
16 fun();
17 return 0;
18 }
Output: 10
If Scope Resolution Operator is placed before a variable name then the global variable is referenced. So if we remove the following line from the above program then it will fail in compilation.
1 int x = 10;
Question 2
1 #include<iostream>
2 using namespace std;
3
4 class Point
5 {
6 private:
7 int x;
8 int y;
9 public:
10 Point(int i, int j); // Constructor
11 };
12
13 Point::Point(int i = 0, int j = 0)
14 {
15 x = i;
16 y = j;
17 cout << "Constructor called";
18 }
19
20 int main()
21 {
22 Point t1, *t2;
23 return 0;
24 }
Output: Constructor called.
If we take a closer look at the statement “Point t1, *t2;:” then we can see that only one object is constructed here. t2 is just a pointer variable, not an object.
Question 3
1 #include<iostream>
2 using namespace std;
3
4 class Point
5 {
6 private:
7 int x;
8 int y;
9 public:
10 Point(int i = 0, int j = 0); // Normal Constructor
11 Point(const Point &t); // Copy Constructor
12 };
13
14 Point::Point(int i, int j)
15 {
16 x = i;
17 y = j;
18 cout << "Normal Constructor called\n";
19 }
20
21 Point::Point(const Point &t)
22 {
23 y = t.y;
24 cout << "Copy Constructor called\n";
25 }
26
27 int main()
28 {
29 Point *t1, *t2;
30 t1 = new Point(10, 15);
31 t2 = new Point(*t1);
32 Point t3 = *t1;
33 Point t4;
34 t4 = t3; //assignment operator
35 return 0;
36 }
Output:
Normal Constructor called
Copy Constructor called
Copy Constructor called
Normal Constructor called
See following comments for explanation:
1 Point *t1, *t2; // No constructor call
2 t1 = new Point(10, 15); // Normal constructor call
3 t2 = new Point(*t1); // Copy constructor call
4 Point t3 = *t1; // Copy Constructor call
5 Point t4; // Normal Constructor call
6 t4 = t3; // Assignment operator call
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:16:34
最新文章
- Entity Framework Core 实现MySQL 的TimeStamp/RowVersion 并发控制
- HotSpot JVM常用参数设置
- java selenium (九) 常见web UI 元素操作 及API使用
- mysql autocommit=OFF导致wordpress 建立数据库连接时出错
- linux centos使用xrdp远程界面登陆
- 【JavaEE企业应用实战学习记录】servlet3.0上传文件
- Shell命令_for
- python中的字符数字之间的转换函数
- PageBase
- redhat_suse双系统引导
- 向SDE图层中添加大量数据时,出现ORA-00604以及ORA-01000的解决办法
- silverlight visifire控件图表制作——silverlight 静态页面xaml
- G - Self Numbers(2.2.1)
- VB ListBox 添加横向滚动条
- 在Linux下编写php扩展
- 你应该学会的Postman用法
- Yii2 Restful Api 401
- Padding Oracle攻击
- JDBC的java驱动安装
- 【一天一道LeetCode】#125. Valid Palindrome