Inheritance and virtual functions

What is inheritance?
  • models the ‘is-a’ relationship

Why do it?
  • Get all member functions and data of the base classes, for free, without having to (re-)write them yourself

Using inheritance
  • Use the : notation(after the class name)
  • Equivalent of Java’s ‘extends'
  • A class could have multiple base class, but more complexity
     
A new access type: protected
  • like private but also allows sub-class members to access the members

Base class and derived class(L12 - p11,p12)
  • Simple single-inheritance: the base class part appears inside the sub-class
  • Simple composition: the contained class part appears inside the containing class

Overriding methods (L12 - p13)
  • Sub-class may replace the function which has same name as in base class

Sub-class objects ARE base class objects (L12 - p14)

Virtual functions - the cost of flexibility (L12 - p18)
  • Adding a virtual function to a class may make the objects of that class bigger
  • A virtual function makes the speed of finding which function to call at runtime slower

Calling base-class functions
  • If a function is virtual, you can still call the base class version from the sub-class version - useful so that you don’t need to report code

Inheritance and constructors(L12 - p25,p26,p27,p28)
  • Construction and destruction
    • Construction occurs in the order
      • Base class first, then derived class
    • Destruction occurs in the order
      • Derived class first, then base class
    • Derived class part of the object can always assume that base class part exists
      • Derived class can assume that the base class has been constructed when the derived class is constructed
      • Derived class can assume that the base class has not yet been destroyed at the point the derived destructor is used
    • Derived class will not exist/be initialised when the base class constructor/destructor is called
      • Do not call virtual function from the constructor or destructor
  • Virtual destructors(L12 - p30,p31,p32,p33,p34)
    • If destructor is not virtual then it will not be called if the object is destroyed through a base class pointer, reference or function - since type of the pointer/reference/function will determine the destructor to call
    • Advice about whether using virtual?
      • If there is already have a virtual functions, then no loss since vtable pointer already exists anyway
      • If there are no other virtual functions, then better not to use a vtable pointer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值