Output of C++ Program | Set 10

Predict the output of following C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
#include<string.h>
using namespace std;
  
class String
{
    char *p;
    int len;
public:
    String(const char *a);
};
  
String::String(const char *a)
{
    int length = strlen(a);
    p = new char[length +1];
    strcpy(p, a);
    cout << "Constructor Called " << endl;
}
  
int main()
{
    String s1("Geeks");
    const char *name = "forGeeks";
    s1 = name;
    return 0;
}

chevron_right


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 (See this and this for details).



Question 2



filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
  
using namespace std;
  
class A
{
    public:
    virtual void fun() {cout << "A" << endl ;}
};
class B: public A
{
    public:
    virtual void fun() {cout << "B" << endl;}
};
class C: public B
{
    public:
    virtual void fun() {cout << "C" << endl;}
};
  
int main()
{
    A *a = new C;
    A *b = new B;
    a->fun();
    b->fun();
    return 0;
}

chevron_right


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 (See this for details). The second line of output is printed by statement “b->fun();”.



Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.