c++ - How come my destructor is not destroying my object and it still retains its member variable values? -


in code don't understand why derived class object not being destroyed though called destructor explicitly. don't know if because didn't include delete or scope can me out? added comments in code illustrate issue

in header file 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 implementation file 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 main file have:

#include "test.h"  int main(){       book b;      b.setbook();      cout<<b.getbook()<<endl;//takes user input     cout<<b.getbook()<<endl;//displays input u put in      b.~book();      cout<<b.getbook()<<endl;//for reason still prints out whatever inputed though called destructor earlier. think display yolo because string saved in constructor of book } 

first of all, don't call destructor explicitly variables automatic storage. destructor called automatically when exit scope in variable defined.

after call,

b.~book(); 

b invalid object.

using b after cause undefined behavior. line after not guaranteed behave in predictable manner.

you have:

cout<<b.getbook()<<endl;//for reason still prints out whatever inputed though called destructor earlier. think display yolo because string saved in constructor of book 

since program subject undefined behavior, pointless trying make sense of does.

also, destructor called on b when function returns, lead undefined behavior.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -