Knowledge points of derived classes

1. There is no extra memory overhead for deriving a class, and the memory required is the memory for storing members.

2. Derived classes generally put the data of the base class in the front:

#define debug qDebug()<<
class A
{
public:
    int a;
};

class B : public A
{
public:
    int b;
};

int main(int argc, char *argv[])
{
    B bb;
    bb.a = 666;
    bb.b = 888;
    debug &bb <<endl<<&bb.a <<&bb.b;
}

So the pointer of the base class (the value of the pointer is the address value) can point to the address of the derived class, because it is the same address value.

3. The pointers and references of the base class can point to the derived class object:

    A & r = bb;
    A * p = &bb;

4. The derived class can access the protection of the base class and the members of the public type, but not the private members. (The most convenient way is to have only public members in the base class)

5. The functions in the base class can be called by reference/pointer:

class A
{
public:
    int a;
    void debugValue(int i)
    {
        debug "A"<<i;
    }
    void debugValue(bool b)
    {
        debug "A"<<b;
    }
};

class B : public A
{
public:
    int b;
    void debugValue(QString str)
    {
        debug "B"<<str;
    }
    void debugValue(int i)
    {
        debug "B"<<i;
    }
};

int main(int argc, char *argv[])
{
    B b;
    b.debugValue("hello");
    b.debugValue(666);
    A & r = b;
    r.debugValue(55);
    r.debugValue(false);
}

7. Use :: in the derived class to easily access the members in the base class:

#define debug qDebug()<<
class A
{
public:
    int a = 999;
    void debugValue()
    {
        debug "hello";
    }
};

class B : public A
{
public:
    int b = 888;
    void debugValue()
    {
        A::a = 444;
        debug A::a;
        A::debugValue();
    }
};

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/114461392