Functionality Behavior

class CBase {
public:
    void print()
    {
        cout<<"In base print func\n";
    };
};

class CDerived: public CBase {
public:
    void print()
    {
        cout<<"In derived print func\n";
    };
};

int main()
{
    CBase b;
    CBase* pb;
    CDerived d;
    CDerived* pd;
    pd->print();
    return 0;
}

The above code works fine, but when I make the print function in the class CBaselike virtual, this leads to a segmentation error.

I think there is one basic logic that I don't know about. Please give your comments, why is this so?

+3
source share
1 answer
CDerived* pd;
pd->print();

The pointer is not initialized -> undefined.

You need

CDerived* pd = new CDerived;
pd->print();

In addition, it does not work normally. Rather, you are not lucky that everything is in order. Virtual submission requires a virtual table, and since the pointer is not initialized, the virtual table pointer does not exist, so it crashes when the functions are virtual.

, - undefined , , .

, :

class CBase {
public:
    int y;
    void print()
    {
        cout<<"In base print func\n" << y;
    };
};

class CDerived: public CBase {
public:
    int x;
    void print()
    {
        cout<<"In derived print func\n" << x;
    };
};

, virtual.

+3

All Articles