Output of C++ Program | Set 2

Predict the output of below C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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)

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics 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.