Class Inheritance

Inheritance: An Is-a Relationship

A banana is a fruit, but a lunch has a banana.

The Need for Virtual Destructors

If the destructors are not not virtual, then just the destructor corresponding to the pointer type is called.

class Brass{

virtual ~Brass(){};

};

class BrassPlus :public Brass{
virtual ~BrassPlus(){};
};

So if a pointer points to a BrassPlus object, the BrassPlus desctructor is called.
And when a BrassPlus destructor finishes, it automatically calls the base-class constructor. Thus, using virtual desctructors ensures that the correct sequence of destructors is called.

BrassPlus dilly;
Brass* pb = &dilly;
Brass& rb = dilly;

It is always allowed for public inheritance without the need for an explict type cast. This rule is part of expressing the is-a relationship.

Things to know About Virtual Methods

  1. Constructors can’t be virtual.Creating a derived object only invokes a derived-class constructor, not a base constructor.
  2. Destructors should be virutal unless a class isn’t to be used a base class.
  3. Friends can’t be virtual functions because friends are not class members, and only members can be virtual functions.

How Virtual Functions Work

The usual way complilers handle virutal functions is to add a hidden member to each object. The hidden member holds a pointer to an array of function addresses. Such an array is usually termed a virtual function table(vtbl).
The vtbl holds the addresses of the virtual functions declared for objects of that class.
在这里插入图片描述
In short, using vrtual functions has the following modest costs in memory and execution speed:

  1. Each object has its size increased by the amount needed to hold an address.
  2. For each class, the compiler a table (an array) of addresses of virtual functions.
  3. For each function call, there’s an extra step of going to a table to look up an address.

Access Control: protected

The protected keyword is like private in that the outside world can access class members in a protected section only by using public class members. The difference between private and protected comes into play only within classes derived from the base class. Members of a derived calss can access protected members of a base class directly, but they cannot directly access private members of the base class.

One way of thinking about Abstract class is to consider it an enforcement of interface. An abstract demands that its pure virtual fuctions be overriden in any concrete derived classes-- forcing the derived class to obey the rules of interface the abstract class has set.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值