PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 7, 2022

[FIXED] Why isn't the derived class destructor being called?

 July 07, 2022     c++, class, declaration, destructor, inheritance     No comments   

Issue

I was doing some practicing with pointers to derived classes and when I ran the code provided underneath,the output I get is

Constructor A
Constructor B
Destructor A

Could someone tell me why is B::~B() not getting invoked here?

class A {
 public:
  A() { std::cout << "Constructor A\n"; }
  ~A() { std::cout << "Destructor A\n"; }
};

class B : public A {
 public:
  B() { std::cout << "Constructor B\n"; }
  ~B() { std::cout << "Destructor B\n"; }
};

int main() {
  A* a = new B;
  delete a;
}

Solution

The static type of the pointer a is A *.

A* a = new B;

So all called member functions using this pointer are searched in the class A.

To call the destructor of the dynamic type of the pointer, that is of the class B, you need to declare the destructor as virtual in class A. For example:

#include <iostream>

class A {
 public:
  A() { std::cout << "Constructor A\n"; }
  virtual ~A() { std::cout << "Destructor A\n"; }
};

class B : public A {
 public:
  B() { std::cout << "Constructor B\n"; }
  ~B() override { std::cout << "Destructor B\n"; }
};

int main() {
  A* a = new B;
  delete a;
}


Answered By - Vlad from Moscow
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing