GeeksforGeeks » C/C++ Programming Questions

A virtual base class doubt

(2 posts)
  • Started 1 year ago by geek4u
  • Latest reply from Angshuman jana

Tags:

  1. geek4u
    guest
    Posted 1 year ago #

    Following program prints 8 on Dev CPP compiler.

    #include<iostream>
    using namespace std;
    
    class base {  int i; };
    
    class d1: public  base { };
    
    class d2: public  base { };
    
    class derived: public d1, public d2 { };
    
    int main(void)
    {
      cout<<sizeof(derived);
      getchar();
      return 0;
    }
    

    But, following program instead of printing 4, is printing 12, why??

    #include<iostream>
    using namespace std;
    
    class base {  int i; };
    
    class d1: public virtual base { };
    
    class d2: public virtual base { };
    
    class derived: public d1, public d2 { };
    
    int main(void)
    {
      cout<<sizeof(derived);
      getchar();
      return 0;
    }
    
  2. Angshuman jana
    guest
    Posted 1 year ago #

    base is declared virtual.....when ever inheriting virtual class it adds 4bytes for virtual property..........once it has inherited virtual property any no of inheritence is same like 1 time inherit


Reply

You must log in to post.

RSS feed for this topic