0

I am getting confused about two code blocks. I will write my expectations and results. So:

I have code like that :

#include <iostream>

class Base {

    void method() {std::cout << "from Base" << std::endl;}
public:
    virtual ~Base() {method();}
    void baseMethod() 
    {
        method();
    }
};

class A : public Base {
    void method() {std::cout << "from A" << std::endl;}
public:
    ~A() {
        std::cout<<"Destructor a" << std::endl;
        method();
    }
    void baseMethod() 
    {
        std::cout<<"Called A" << std::endl;
        method();
    }
};

int main(void) {
    Base* base = new A;
    base->baseMethod();
    delete base;
    return 0;
}

and output in the terminal :

from Base
Destructor a
from A
from Base

Questions is, method() is not virtual. For example, in baseMethod() call in main function, calling base->baseMethod() calls Base classes baseMethod and inside baseMethod(), calling method(). Since method() is not virtual, it calls Base classes method and prints "From Base". Its OK.

But.. When deleting base point with line

delete Base;

Since Base Classes Destructor is virtual, its calling Derived Classes destructor ~A(). Inside this destructor, method() calls. But by looking the output, this method() call, calls the Class A's method() and prints from A to the screen. But method() is not virtual . Destructor called by base classes pointer, to shortly, I am expecting From B in destructor A, but it prints From A. How it is ? .

My expectation :

from Base
Destructor a
from Base
from Base

When I add virtual to this line :

class Base {

    virtual void method() {std::cout << "from Base" << std::endl;}

Output is :

from A
Destructor a
from A
from Base

You can see, behaviour in method() which calls from baseMethod is changed and outputs changed too. But In ~A() destructor, behaviour is same.

tango-1
  • 330
  • 1
  • 10
  • You refer to "B" (B in destructor A), what's that? Also, don't add PS, just [edit] your question to clarify things. Also, please provide the received output and the expected output, then explain why you expect things. That makes your question much clearer and more understandable. – Ulrich Eckhardt Jan 13 '19 at 11:45

1 Answers1

0

The body of ~A() is in the lexical scope of A. As such, the call method() in ~A() is statically bound to A::method. No more no less.

Since ~A() is being called, that in turn calls this statically bound member function.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458