Jackey
Jackey

Reputation: 75

How to delete subclass pointer where use parent pointer as formal parameters in function?

I meet a question when I delete subclass point. I want to delete subclass pointer use parent class pointer as formal parameters. And there is my code likes follows.

class Test
{
public:
    virtual ~Test() = default;
    int a =10;
};
class TestChild : public Test
{
public:
    int c ;
};

class A
{
public:
    A(){
        TestChild* tc = new TestChild();
        tc->c = 19;
        delTest(tc);
    }
    void delTest(Test* &ds){
        delete ds;
        ds = nullptr;
    }
};

Bulid the project I will get an error:

cannot bind non-const lvalue reference of type 'Test*&' to an rvalue of type 'Test*'

If I modify the function to void delTest(Test**ds){ delete *ds; *ds=nullptr;} and delTest(&tc);, I also got an error:

invalid conversion from 'TestChild**' to 'Test**'

What do I need to do to make my code work?

Upvotes: 0

Views: 69

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

What do I need to do to make my code work?

You could make function templates to support delete and delete[] + setting the pointer to nullptr:

template<typename T>
void delete_and_nullify_single_element_pointer(T*& ptr) {
    delete ptr;
    ptr = nullptr;
}

template<typename T>
void delete_and_nullify_array_pointer(T*& ptr) {
    delete[] ptr;
    ptr = nullptr;
}
class A {
public:
    A() {
        TestChild* tc = new TestChild;
        tc->c = 19;
        delete_and_nullify_single_element_pointer(tc);
    }
};

Upvotes: 1

Related Questions