zoukankan      html  css  js  c++  java
  • Output of C++ Program | Set 10

      Predict the output of following C++ programs.

    Question 1

     1 #include<iostream>
     2 #include<string.h>
     3 using namespace std;
     4 
     5 class String
     6 {
     7     char *p;
     8     int len;
     9 public:
    10     String(const char *a);
    11 };
    12 
    13 String::String(const char *a)
    14 {
    15     int length = strlen(a);
    16     p = new char[length +1];
    17     strcpy(p, a);
    18     cout << "Constructor Called " << endl;
    19 }
    20 
    21 int main()
    22 {
    23     String s1("Geeks");
    24     const char *name = "forGeeks";
    25     s1 = name;
    26     return 0;
    27 }

      Output:

      Constructor called
      Constructor called
      The first line of output is printed by statement “String s1(“Geeks”);” and the second line is printed by statement “s1 = name;”. The reason for the second call is, a single parameter constructor also works as a conversion operator.

     

    Question 2

     1 #include<iostream>
     2 
     3 using namespace std;
     4 
     5 class A
     6 {
     7 public:
     8     virtual void fun() 
     9     {
    10         cout << "A" << endl ;
    11     }
    12 };
    13 class B: public A
    14 {
    15 public:
    16     virtual void fun() 
    17     {
    18         cout << "B" << endl;
    19     }
    20 };
    21 class C: public B
    22 {
    23 public:
    24     virtual void fun() 
    25     {
    26         cout << "C" << endl;
    27     }
    28 };
    29 
    30 int main()
    31 {
    32     A *a = new C;
    33     A *b = new B;
    34     a->fun();
    35     b->fun();
    36     return 0;
    37 }

      Output:

      C
      B
      A base class pointer can point to objects of children classes. A base class pointer can also point to objects of grandchildren classes. Therefor, the line “A *a = new C;” is valid. The line “a->fun();” prints “C” because the object pointed is of class C and fun() is declared virtual in both A and B. The second line of output is printed by statement “b->fun();”.

      

      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:56:12

  • 相关阅读:
    python函数
    python正则表达式
    FileStorage
    dietpi请暂时不要升级为jessie
    不从SD卡启动树莓派2
    树莓派2系统DietPi简单安装配置使用介绍
    树莓派笔记之使用netselect选择最快Raspbian软件源
    树莓派系统介绍:DIetPi
    【翻译】树莓派2:关闭无线网卡电源管理功能
    树莓派2安装使用小米WIfi(360 小度 腾讯wifi)
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3445902.html
Copyright © 2011-2022 走看看