Protected Base Destructor

closed account (oGhfSL3A)
Hello

I want to create a derived object that can decide weather or not it gets deleted.
this is what I tried, and it works, but it shows a warning:

warning: deleting object of polymorphic class type 'derived' which has non-virtual destructor might cause undefined behaviour.

So, is this safe?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

class base{
public:
    base(){
        std::cout << "creating base\n";
    }
    virtual bool kill()=0;      //returns false if object should not be deleted for some reason
protected:
    ~base(){
        std::cout << "destroying base\n";
    }
};

class derived:public base{
public:
    derived(): base(){
        std::cout << "creating derived\n";
    }
    bool kill(){
        delete this;
    }
protected:
    ~derived(){
        std::cout << "destroying derived\n";
    }
};

int main(){
    base* pBase= new derived;
    pBase->kill();
    return 0;
}


thanks
Last edited on
So, is this safe?
No:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

class base{
public:
    base(){
        std::cout << "creating base\n";
    }
    virtual bool kill()=0;      //returns false if object should not be deleted for some reason
protected:
    ~base(){
        std::cout << "destroying base\n";
    }
};

class derived:public base{
public:
    derived(): base(){
        std::cout << "creating derived\n";
    }
    bool kill(){
        delete this;
    }
protected:
    ~derived(){
        std::cout << "destroying derived\n";
    }
};

class derived2:public derived{
public:
    derived2() {
        std::cout << "creating derived2\n";
    }
protected:
    ~derived2(){
        std::cout << "destroying derived2\n";
    }
};

int main(){
    base* pBase= new derived2;
    pBase->kill();
    return 0;
}
creating base
creating derived
creating derived2
destroying derived
destroying base 


'undefined behaviour' is always a bad thing
closed account (oGhfSL3A)
OK thanks didn't think of that.
Topic archived. No new replies allowed.