Saturday, July 30, 2011

Understanding C++ inherit for data members

author:feiyinzilgd
Work have a such problem latterly,all subclass must have one data membes.The best way to place bass class and use protected qualifier for regulated interface.

The code about my question:
class BaseB;
class BaseA
{
    Base();
    virtual ~Base();

    //...other operation


protected:

    BaseB *m_p;
}

This is simple,BaseA and BaseB was base class,BaseA have a pointer for BaseB,Because you will use oplymorphic type on subclass later.

jump out of this question,All most speciality of c++ language through virtual functions table to realize.

how inherit of data members realize?How class and class objects memory situation?Let's us to watch code first:
#include <stdio.h>
#include <iostream>

using namespace std;

class Base
{
public:
    Base(){}
    void operation(){}

protected:
    char a;
    int b;
};

class A: public Base
{
public:
    short c;
};

int main(int argc, char **argv)
{
    A obj;
    cout << "the size of the obj is " << sizeof(obj) << endl;
}

Output:the size of the obj is 12 

Analyse:1+3+4+2+2 = 12

In fact That is:
struct _data
{
     char a;
     int b;
     short c;
}
The structure align at four types in memory.

The code explain:

1,Non-virtual function don't use space of class objects,Non virtual fuction isn't run time,it mean address of function was get on compilation phase and call to function already replace to entry address of function by compiler during compilation.

2,Derived class copyed data by base class inherit.Above code,Derived A possess:member method of a,b. member method possess void operation.
In memory:
_____________________________________


|__________char a____________________ _|


|__________int b_______________________|


|__________short c_____________________|

Watch here,You can know to realized about data members inherit.

Next watch:
#include <stdio.h>
#include <iostream>

using namespace std;

class Base
{
public:
    Base(){ a = 0; b = 0;}
    virtual void operation(){ b = 12;}
    virtual void print(){}
protected:
    char a;
    int b;
};

class A: public Base
{
public:
    short c;
    void operation() { b = 24; }
    void print() { cout << "result is " << b << endl;}
};

int main(int argc, char **argv)
{
    A obj;
    Base *p = &obj;
    //cout << "the size of the obj is " << sizeof(obj) << endl;
    p->Base::operation();//注意:这里是强行调用基类的方法
    p->print();//使用调用的事派生类的print
    p->operation();//调用派生类A的方法
    p->print();
}
Output:
result is 12
result is 24

No comments:

Post a Comment