In my code I don't understand why my derived class object is not being destroyed even though I called the destructor explicitly. I don't know if its because I didn't include delete or something to do with the scope but can you help me out? I added comments in my code to help illustrate my issue
In my header file I have:
#ifndef test_test_h
#define test_test_h
#include <iostream>
#include <string>
using namespace std;
class test{
public:
test();
void setName();
string getName();
private:
string name;
};
class book:public test{
public:
book();
~book();
void setBook();
string getBook();
private:
string bookName;
};
#endif
In my implementation file I have:
#include "test.h"
test::test()
{
cout<<"calling base construtor"<<endl;
name="hi";
}
book::book()
{
cout<<"Calling derived constructor"<<endl;
bookName="yolo";
}
test::~test()
{
cout<<"calling test destructor"<<endl;
}
book::~book()
{
cout<<"calling book destructor"<<endl;
}
void test::setName()
{
cout<<"Input name"<<endl;
cin>>name;
}
string test::getName()
{
return name;
}
void book::setBook()
{
cout<<"Input name"<<endl;
cin>>bookName;
}
string book::getBook()
{
return bookName;
}
In my main file I have:
#include "test.h"
int main(){
book b;
b.setBook();
cout<<b.getBook()<<endl;//takes user input
cout<<b.getBook()<<endl;//displays the input u put in
b.~book();
cout<<b.getBook()<<endl;//for some reason it still prints out whatever you inputed even though I called the destructor earlier. I would think it would display yolo because that string is saved in the constructor of book
}
First of all, don't call the destructor explicitly for variables with automatic storage. The destructor will be called automatically when you exit the scope in which the variable is defined.
After you call,
b
is an invalid object.Using
b
after that is cause for undefined behavior. The line after that is not guaranteed to behave in any predictable manner.You have:
Since the program is subject to undefined behavior, it is pointless trying to make sense of what it does.
Also, the destructor will be called on
b
when the function returns, which will lead to undefined behavior.