Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Size of inherited class! (http://www.programmingforums.org/showthread.php?t=12503)

sharadpro Feb 4th, 2007 12:23 PM

Size of inherited class!
 
:

#include<iostream>
using namespace std;

class X
{
int x;
public:
int y;
protected:
int z;
};

class Y : public X
{
int a;
public:
int b;
protected:
int c;
};

int main()
{
cout<<sizeof(Y);
return 0;
}



According the output (24 on my machine) , even the variable x which was private in class X is being considered as a part of class Y?
Please explain!

lectricpharaoh Feb 4th, 2007 12:33 PM

What's to explain? Those private members will still be there, even if they ae not directly accessible. However, this doesn't mean they are not accessible at all; try putting a pair of get/set methods in the base class, and then call them.

The point is that private data members are (generally) intended to help the class keep track of its own internal state. Deriving a new class from this class doesn't mean it no longer has this responsibility, thus, it should have all the original members.

DaWei Feb 4th, 2007 1:14 PM

That's why it's called 'inheritance' ;). Those other thangys are access modifiers.

pegasus001 Feb 4th, 2007 2:43 PM

Quote:

Originally Posted by sharadpro (Post 123481)
even the variable x which was private in class X is being considered as a part of class Y?

They are family, it counts.


All times are GMT -5. The time now is 2:00 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC