[CPP] Inheritance and virtual function

Inheritance

how to use the inheritance?
class MyClass : public MySuperClass{
//Do something
}
  • Equivalent of Java’s extends
  • A class can have multiple base classes

public/private/protected

  • public: Anything can access the member
  • private: Only class members can access the members, not even sub-class members
  • protected: like private but also allows sub-class member to access the members

Overriding methods

If there is no override for some method

The method will be unchanged in sub-class and use the base class method.

There is overriden method and we don’t use virtual

enter image description here
Because the subclass object is assigned to a baseclass pointer, so it will cast to baseclass.

You can choose which you want to apply (by making the function virtual or not)

  • When you use virtual, the functions in the sub-class are used (because the object is really of the sub-class type)
  • When you don’t use virtual, the functions in the base-class are used (because the pointer type is used to determine the function to use)
enter image description here
  • Adding a virtual function to a class may make the objects of that class bigger
  • Looking up which function to call at runtime is slower when functions are virtual(This is why the default is to not have virtual functions)

If a function is virtual, you can still call the base class version from the sub-class version

enter image description here

Inheritance and constructors

Just create a sub-class

enter image description here
result is base-sub-~sub-~base

new a sub-class on heap and delete it

enter image description here
result remains the same

new a sub-class on heap and assign to superclass

enter image description here
There is no destructor for subclass!

if we add virtual to destructor of superclass

enter image description here
destructor come back again
  • Construction occurs in the order: Base class first, then derived class
  • Destruction occurs in the order: Derived class first, then base class
  • Derived class will NOT exist/be initialised when the base class constructor/destructor is called, so:
  • Do not call virtual functions from the constructor or destructor

Should we make the destructor virtual or not?

Make it virtual if and only if there are ANY other virtual functions.
No loss since vtable pointer already exists anyway.
If there are no other virtual functions AND you do not expect the object to be deleted through a pointer or reference to the base class THEN do not make your destructor virtual–Otherwise you add an unnecessary vtable pointer (or equivalent) to objects

评论

此博客中的热门博文

[MLE] W2 Multivariate linear regression

[MLE] W1 Introduction

[AIM] MetaHeuristics