Open In App
Related Articles

Output of C++ Program | Set 16

Improve Article
Improve
Save Article
Save
Like Article
Like

Predict the output of following C++ programs.

Question 1




#include<iostream>
using namespace std;
  
class Base 
{
public:
    int fun()      { cout << "Base::fun() called"; }
    int fun(int i) { cout << "Base::fun(int i) called"; }
};
  
class Derived: public Base 
{
public:
    int fun(char x)   { cout << "Derived::fun(char ) called"; }
};
  
int main() 
{
    Derived d;
    d.fun();
    return 0;
}


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



Question 2




#include<iostream>
using namespace std;
class Base 
{
   protected:
      int x;
   public:
      Base (int i){ x = i;}
};
  
class Derived : public Base 
{
   public:
      Derived (int i):x(i) { }
      void print() { cout << x ; }
};
  
int main()
{
    Derived d(10);
    d.print();
}


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.




#include<iostream>
using namespace std;
class Base {
   protected:
      int x;
   public:
      Base (int i){ x = i;}
};
  
class Derived : public Base {
   public:
      Derived (int i):Base(i) { }
      void print() { cout << x; }
};
  
int main()
{
    Derived d(10);
    d.print();
}


Output:

 10 

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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Sep, 2018
Like Article
Save Article
Previous
Next
Similar Reads