Skip to content
Related Articles

Related Articles

Output of C++ Program | Set 2
  • Difficulty Level : Medium
  • Last Updated : 10 Jul, 2018
GeeksforGeeks - Summer Carnival Banner

Predict the output of below C++ programs.

Question 1




#include<iostream>
using namespace std;
 
class A { 
 public:
    A(int ii = 0) : i(ii) {}
    void show() { cout << "i = " << i << endl;}
 private:
    int i;
};
 
class B {
 public:
    B(int xx) : x(xx) {}
    operator A() const { return A(x); }
 private:
    int x;
};
 
void g(A a)
{  a.show(); }
 
int main() {
  B b(10);
  g(b);
  g(20);
  getchar();
  return 0;

Output:
i = 10
i = 20

Since there is a Conversion constructor in class A, integer value can be assigned to objects of class A and function call g(20) works. Also, there is a conversion operator overloaded in class B, so we can call g() with objects of class B.



Question 2






#include<iostream>
using namespace std;
  
class base {
    int arr[10];     
};
  
class b1: public base { };
  
class b2: public base { };
  
class derived: public b1, public b2 {};
  
int main(void)
  cout<<sizeof(derived);
  getchar();
  return 0;
}

Output: If integer takes 4 bytes, then 80.

Since b1 and b2 both inherit from class base, two copies of class base are there in class derived. This kind of inheritance without virtual causes wastage of space and ambiguities. virtual base classes are used to save space and avoid ambiguities in such cases. For example, following program prints 48. 8 extra bytes are for bookkeeping information stored by the compiler (See this for details)




#include<iostream>
using namespace std;
  
class base {
  int arr[10];     
};
  
class b1: virtual public base { };
  
class b2: virtual public base { };
  
class derived: public b1, public b2 {};
  
int main(void)
  cout<<sizeof(derived);
  getchar();
  return 0;
}

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :