Output of C++ Program | Set 15

Predict the output of following C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
class A
{
public:
    void print() { cout << "A::print()"; }
};
  
class B : private A
{
public:
    void print() { cout << "B::print()"; }
};
  
class C : public B
{
public:
    void print() { A::print(); }
};
  
int main()
{
    C b;
    b.print();
}

chevron_right


Output: Compiler Error: ‘A’ is not an accessible base of ‘C’
There is multilevel inheritance in the above code. Note the access specifier in “class B : private A”. Since private access specifier is used, all members of ‘A’ become private in ‘B’. Class ‘C’ is a inherited class of ‘B’. An inherited class can not access private data members of the parent class, but print() of ‘C’ tries to access private member, that is why we get the error.





Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
class base
{
public:
    virtual void show()  { cout<<" In Base \n"; }
};
  
class derived: public base
{
    int x;
public:
    void show() { cout<<"In derived \n"; }
    derived()   { x = 10; }
    int getX() const { return x;}
};
  
int main()
{
    derived d;
    base *bp = &d;
    bp->show();
    cout << bp->getX();
    return 0;
}

chevron_right


Output: Compiler Error: ‘class base’ has no member named ‘getX’
In the above program, there is pointer ‘bp’ of type ‘base’ which points to an object of type derived. The call of show() through ‘bp’ is fine because ‘show()’ is present in base class. In fact, it calls the derived class ‘show()’ because ‘show()’ is virtual in base class. But the call to ‘getX()’ is invalid, because getX() is not present in base class. When a base class pointer points to a derived class object, it can access only those methods of derived class which are present in base class and are virtual.



Question 3

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
class Test
{
    int value;
public:
    Test(int v = 0) { value = v; }
    int getValue()  { return value; }
};
  
int main()
{
    const Test t;
    cout << t.getValue();
    return 0;
}

chevron_right


Output: Compiler Error
In the above program, object ‘t’ is declared as a const object. A const object can only call const functions. To fix the error, we must make getValue() a const function.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


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