Assume that an integer takes 4 bytes and there is no alignment in following classes, predict the output.
#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);
return 0;
}
|
(A) 40
(B) 80
(C) 0
(D) 4
Answer: (B)
Explanation: 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);
return 0;
}
Quiz of this Question
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 Jun, 2021
Like Article
Save Article