Open In App

Output of C++ Program | Set 15

Last Updated : 27 Dec, 2016
Improve
Improve
Like Article
Like
Save
Share
Report

Predict the output of following C++ programs.

Question 1




#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();
}


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




#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;
}


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




#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;
}


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads