Output of C++ Program | Set 16
Predict the output of following C++ programs.
Question 1
1 #include<iostream>
2 using namespace std;
3
4 class Base
5 {
6 public:
7 int fun()
8 {
9 cout << "Base::fun() called";
10 }
11 int fun(int i)
12 {
13 cout << "Base::fun(int i) called";
14 }
15 };
16
17 class Derived: public Base
18 {
19 public:
20 int fun(char x)
21 {
22 cout << "Derived::fun(char ) called";
23 }
24 };
25
26 int main()
27 {
28 Derived d;
29 d.fun();
30 return 0;
31 }
Output: Compiler Error.
In the above program, fun() of base class is not accessible in the derived class. If a derived class creates a member method with name same as one of the methods in base class, then all the base class methods with this name become hidden in derived class.
Question 2
1 #include<iostream>
2 using namespace std;
3 class Base
4 {
5 protected:
6 int x;
7 public:
8 Base (int i)
9 {
10 x = i;
11 }
12 };
13
14 class Derived : public Base
15 {
16 public:
17 Derived (int i):x(i)
18 {
19 }
20 void print()
21 {
22 cout << x ;
23 }
24 };
25
26 int main()
27 {
28 Derived d(10);
29 d.print();
30 }
Output: Compiler Error
In the above program, x is protected, so it is accessible in derived class. Derived class constructor tries to use initializer list to directly initialize x, which is not allowed even if x is accessible. The members of base class can only be initialized through a constructor call of base class.
Following is the corrected program.
1 #include<iostream>
2 using namespace std;
3 class Base
4 {
5 protected:
6 int x;
7 public:
8 Base (int i)
9 {
10 x = i;
11 }
12 };
13
14 class Derived : public Base
15 {
16 public:
17 Derived (int i):Base(i)
18 {
19 }
20 void print()
21 {
22 cout << x;
23 }
24 };
25
26 int main()
27 {
28 Derived d(10);
29 d.print();
30 }
Output:
10
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 16:34:25
最新文章
- 移动开发框架剖析(二) Hammer专业的手势控制
- Azure VM上传小文件
- protobuf框架简介
- nsstring字符串重组
- ASP.NET之Ajax系列(二)
- sqlite 对表的操作
- jquery.validate.js使用id验证控件
- Csharp volatile 关键字
- UWP入门一 7天酒店客户端源码及说明
- Linux imagemagic(转载)
- 自定义 select 下拉菜单
- Delphi语言最好的JSON代码库 mORMot学习笔记1
- json2.js参考
- 【原创】大叔经验分享(43)logstash设置jdbc_default_timezone后报错
- python 数据分析算法(决策树)
- JavaScript在IE和Firefox的不兼容问题解决方法总结
- 【1】【JUC】JDK1.8源码分析之ReentrantLock
- openssl版本升级操作记录【转】
- IdentityServer4:Endpoint
- IntelliJ IDEA使用心得
热门文章
- Docker配置tomcat端口映射后无法访问(404)
- Java 在PPT中创建散点图
- PicGo+Gitee(码云)中的404错误解决方案
- 【Python+postman接口自动化测试】(3)什么是接口测试?
- 【Java】数组Array
- 该虚拟机似乎正在使用中。如果该虚拟机未在使用,请按“获取所有权(T)”按钮获取它的所有权
- mysql流程控制结构case when
- Vue.js教程 2.体验Vue
- Part 32 AngularJS controller as syntax
- php 图像和水印