Please tell me why the c++ code error is coming up

Asked 2 years ago, Updated 2 years ago, 22 views

#include<iostream>

using namespace std;

class First
{
public:
    void SimpleFunc() { cout << "First" << endl; };
};

class Second :public First
{
public:
    virtual void SimpleFunc() { cout << "Second" << endl; };

};


int main(void)
{
    First* ptr = new First();
    ptr->SimpleFunc();
    delete ptr;

    ptr = new Second();
    ptr->SimpleFunc();
    delete ptr;

    return 0;
}

void SimpleFunc() {cout <<"First" << endl;}; If you set this part to virtual, it works normally If I don't, there's an error.

Error in last delete ptr What's the reason?

c++

2022-09-20 19:14

2 Answers

Modify delete ptr; on the sixth line of the main function to delete (Second*)ptr;.

There seems to be no problem with the rest.

Unless the ptr variable must be recycled, modifying the main function as shown below results in the same result.

    First* ptr_first = new First();
    ptr_first->SimpleFunc();
    delete ptr_first;

    Second* ptr_second = new Second();
    ((First*)ptr_second)->SimpleFunc();
    delete ptr_second;


2022-09-20 19:14

If you look at the source code that you wrote, The Second class inherits the First class.

The First type pointer variable (ptr here) can point to the First object or any object that inherits the First directly or indirectly.

Therefore, it can also refer to the Second object that inherited First First* type, but ptr = newSecond(); is available.

However, member access is only possible for members defined in the class corresponding to the pointer type (First here)

ptr = new Second();
ptr->SimpleFunc();

This syntax calls First::SimpleFunc().

Use 'virtual functions' to avoid this situation.

If you use the virtual keyword for SimpleFunc() in the First class, the last overridden Second::SimpleFunc() is called.

I think you tried to write the source code as below, but if you squeeze it like this, there will be no error.

The virtual keyword can be used to invoke the member function of Second when ptr type First* points to Second object.

#include<iostream>

using namespace std;

class First
{
public:
    virtual void SimpleFunc() { cout << "First" << endl; };
};

class Second :public First
{
public:
    void SimpleFunc() { cout << "Second" << endl; };

};


int main(void)
{
    First* ptr = new First();
    ptr->SimpleFunc();

    ptr = new Second();
    ptr->SimpleFunc();
    delete ptr;

    return 0;
}


2022-09-20 19:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.