Virtual destructor Problem

Discussion in 'C++' started by humhaingaurav, Apr 24, 2008.

  1. humhaingaurav

    humhaingaurav New Member

    Joined:
    Jan 28, 2008
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Hi Guys,
    Can someone please explain me why this is happening
    Code:
    #include<iostream>
    using namespace std;
    
    class a {
    
    public:
    int a1; // If I remove this it'll work fine
    a() {
    cout << "Constructor of a \n";
    }
    ~a() {
    cout << "Destructor of a \n";
    }
    
    };
    
    class b : public a{
    
    public:
    b() {
    cout << "constructor of b \n";
    }
    virtual ~b() { // If I remove virtual from here ... it'll work fine
    cout << "destructor of b\n";
    }
    
    };
    
    int main() {
    a *p = new b;
    
    delete p;
    
    return 0;
    }
    
    Result is :
    Constructor of a
    constructor of b
    Destructor of a
    a.out(1563) malloc: *** error for object 0x100154: Non-aligned pointer
    being freed
    *** set a breakpoint in malloc_error_break to debug
    ----------------------------------------------------------------

    I know that if I'll put virtual in front of the destructor of the base class code will work fine. But, I want to use it the above way. Can someone please explain me the reason behind this kind of behavior?

    Thanks in advance
     
    Last edited by a moderator: Apr 24, 2008

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice