抽象类、继承和虚拟析构函数
Abstract classes, inheritance and virtual destructors
即使B
的析构函数不是virtual
,我仍然可以通过B
指针调用C
的析构函数。
这是否意味着只有最外层的抽象class需要有一个virtual
析构函数?
如果是这样,为什么它会这样工作?
是因为B
继承了A
的析构函数吗?
#include <iostream>
struct A {
virtual ~A() {
std::cout << "~A\n";
}
virtual void
function_a() = 0;
};
struct B : A {
/*
virtual ~B() {
std::cout << "~B\n";
}
*/
virtual void
function_b() = 0;
};
struct C : B {
~C() override {
std::cout << "~C\n";
}
void
function_a() override {
std::cout << "function_a\n";
}
void
function_b() override {
std::cout << "function_b\n";
}
};
int
main() {
B * b = new C();
b->function_a();
b->function_b();
delete b;
}
B
和C
的析构函数也是virtual
。析构函数不会被继承,但是如果基础class的析构函数是virtual
,派生的析构函数会覆盖它并且也是virtual
;尽管 virtual
是否明确指定。
Even though destructors are not inherited, if a base class declares its destructor virtual
, the derived destructor always overrides it.
和
Then this function in the class Derived is also virtual
(whether or not the keyword virtual
is used in its declaration) and overrides Base::vf
(whether or not the word override
is used in its declaration).
即使B
的析构函数不是virtual
,我仍然可以通过B
指针调用C
的析构函数。
这是否意味着只有最外层的抽象class需要有一个virtual
析构函数?
如果是这样,为什么它会这样工作?
是因为B
继承了A
的析构函数吗?
#include <iostream>
struct A {
virtual ~A() {
std::cout << "~A\n";
}
virtual void
function_a() = 0;
};
struct B : A {
/*
virtual ~B() {
std::cout << "~B\n";
}
*/
virtual void
function_b() = 0;
};
struct C : B {
~C() override {
std::cout << "~C\n";
}
void
function_a() override {
std::cout << "function_a\n";
}
void
function_b() override {
std::cout << "function_b\n";
}
};
int
main() {
B * b = new C();
b->function_a();
b->function_b();
delete b;
}
B
和C
的析构函数也是virtual
。析构函数不会被继承,但是如果基础class的析构函数是virtual
,派生的析构函数会覆盖它并且也是virtual
;尽管 virtual
是否明确指定。
Even though destructors are not inherited, if a base class declares its destructor
virtual
, the derived destructor always overrides it.
和
Then this function in the class Derived is also
virtual
(whether or not the keywordvirtual
is used in its declaration) and overridesBase::vf
(whether or not the wordoverride
is used in its declaration).