We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,420 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Memory allocation difference between virtual and non virtual class

I have a base class and two derived class. One derived class which inherits base class as virtual and another one as non virtual. I have given below my codin.

// This program uses virtual base classes.
    #include <iostream>
    using namespace std;
    class base {
    public:
    int i;
    };
    // derived inherits base as not virtual
    class derived : public base {
    public:
    int x;
    };
    // derived1 inherits base as virtual.
    class derived1 : virtual public base {
    public:
    int j;
    };
    int main()
    {
    base b;
    cout<<endl<<sizeof(b)<<" ";
    derived obn;
    cout<<sizeof(obn)<<" ";
    derived1 ob1;
    cout<<sizeof(ob1);
    
    return 0;
    }

After running this program i get the below output

4
8
12 > "Why the virtual derived class having 12 bytes? "

2
Contributors
1
Reply
7 Hours
Discussion Span
1 Year Ago
Last Updated
2
Views
infantheartlyje
Light Poster
30 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Given the size difference, I'd say that your compiler implements virtual bases using a virtual base pointer (much like the better known virtual table pointer for polymorphism). Extra bookkeeping is required to maintain the shared instance, because the compiler can't simply stack the instances as in non-virtual inheritance.

Narue
Bad Cop
Team Colleague
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 54

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0694 seconds using 2.72MB