I saw the following sentences from a book
“A difference between a destructor and other member functions is that, if a regular member function has a body at the derived class, only the version at Derived class gets executed. Whereas in case of destructors, both derived as well as base class versions get executed.”

I don't quite understand the above sentences

If I have a base class B and a derived class D
both have a member function say m,

suppose BO is a base class object, if I call BO.m, the member function in B will not be executed but the member function in D will be executed?

Recommended Answers

All 3 Replies

No, if its type BO then it will be BO.m, if its type DO (derived object) then it would be DO.m But when a destructer is called, it would execute D constructor first (i beleive this is the order) then B destructor.

The M method in the derived class masks the M method in the super class, so calling the M method on the derived class will always execute the M method in the derived class, but never the M method in the super class

Chris

No.

If you have a derived class object DO and call DO.m then only DO.m is executed. But if you call the destructor both the derived class destructor and the base class destructor get called (in that order).

There are more difference. For instance, when an object gets destroyed,
its destructor is called. Whereas when an object gets destroyed, its
member function might not be called. Also a destructor has no return
type where as an member function could.

Looks like what your confused about is polymorphism. Take a look
at this code :

#include<iostream>
using namespace std;

struct A{ virtual void f(){ cout << "A\n"; } };
struct B : A{  void f(){ cout << "B\n"; } };

void print(A& a){ a.f(); }

int main(){
 A a = A();
 B b = B();
 a.f(); // prints "A";
 b.f(); //prints "B";
 print(a); //prints "A";
 print(b); //prints "B" but prototype expects A
}

a.f() calls its f() function.
b.f() calls its f() function.
print(a) calls a.f().
print(b) calls b.f() even though the prototype expects an object of A.
Thats called polymorphism.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.