1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

size of object in publically inherited class

Discussion in 'C++' started by hardik31385, Mar 30, 2009.

  1. hardik31385

    hardik31385 New Member

    hello Experts ,
    i am conduced in following program output..
    Code:
    #include<iostream.h>
    #include<conio.h>
    class base
    {
        int i;
    };
    class derived1:base
    {
        int j;
    };
    class derived2:base
    {
        int k;
    };
    class derived3:derived1,derived2
    {
        int l;
    };
    void main()
    {
        clrscr();
        derived3 a;
        cout<<sizeof(a);
    
    
        getch();
    
    }
    
    i m getting output 10 ...but how it is possible as hear public data member's , and class is inherited as public , how it is possible to inherit private member?:crazy:
     
    Last edited by a moderator: Mar 31, 2009
  2. xpi0t0s

    xpi0t0s Mentor

    I guess sizeof int is 2 on your system.
    In derived3 you have derived3::l, derived1::j, derived2::k, derived1::base::i and derived2::base::i, which is five int's. Hence 10.
    When you derive a class you get the whole lot, private or otherwise.
     
  3. hardik31385

    hardik31385 New Member

    I think you r right , is thr any case of default constructor? because , that program act like that , it will call default constructor , and default constructor , will return sizeof(this) for individual class.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Every class X has a default compiler-provided constructor X::X() which you can override if necessary.
    In your example five constructors will be called; two bases, derived1, derived2 and derived3.
    Not sure which order it'll be done in or if that order is guaranteed, but you could try adding something like
    Code:
    class derived2:base
    {
        int k;
    public:
        derived2() { cout << "In derived2 ctor\n"; }
    };
    
    to see what's going on internally.

    I'm not sure I understand what you're getting at regarding constructors and sizeof this; there is only one sizeof called and that's sizeof(a). The compiler can determine the size from the code; this isn't determined at runtime.
     
  5. Mridula

    Mridula New Member

    Irrespective of access -specifiers, the sizeof an object is calculated. And it is decided at compile time itself.
     
  6. Mridula

    Mridula New Member

    It is nothing but number of bytes needed to store that particulear object. Though, private members are not accessible to derived, still it would have taken enough space to store it's base classes private variables as part of it's memory-map.
     

Share This Page