`

c++ type of inheritance

    博客分类:
  • c++
c++ 
阅读更多

There are 3 types of inheritances in classes inheritance in C++; they are 

 

  • public inheritance 
  • protected inheritance
  • protected inheritance

 

as for the synonym of the type of inheritances, public inheritance is also know as type inheritance, while the private  inheritance is also know as implementation inheritancfe. 

 

 

A public derivation is refered to as type inhertitance, the dervied class is a subtype of the bse classes; it overrides the implementation of all type-specific member funcitons. of the base class while inheriting those that are shared.  The derived class in general reflects is-a relationship

 

While we know a lots can be found abou the public inheritance, here we are not going into details further. 

 

 

A private derivation is refered to as implementation inheritance, the derived class does not support the public interface of hte base directly. rather, it wishes to reuses the implementation of the base class while providing its own interface. To illustrate the issues involved, let's implements a PeekbackStack. 

 

Let's see an examle. 

 

suppose that we are subclass a IntArray class (a custom class) and provide additional functionality such as the ability to peek the back of the stack, which we call the subclass PeekbackStack.

 

for illustration purpose, this is the simplified version of IntArray code.

 

class IntArray
{
public:
	IntArray(int size) : _size(size) {
		init(size, 0);
	}
	IntArray(const IntArray & rhs) { 
		init(rhs.size(), rhs.ia);
	}
	int size() const { return _size; }
	int& operator[](int index) { return ia[index]; }

	virtual ~IntArray() { 
		delete[] ia;
	}
private:
	void init(int sz, int * array_) { 
		_size = sz;
		ia = new int[_size];
		for (int i = 0; i < _size; ++i) {
			if (! array_)
				ia[i] = 0;
			else ia[i] = array_[i];
		}
	}
protected:
	int _size;
	int *ia;
};

 

if you are using the public inheritance, you might implement the code as follow. 

 

 

class PeekbackStack : public IntArray
{
private:
	const int static bos = -1;
public:
	explicit PeekbackStack(int size) : IntArray(size), _top(bos) { }

	bool empty() const { return _top == bos;  } 
	bool full() const { return _top == size() - 1; }
	bool top() const { return _top; } 

	int pop() { 
		if (empty()) {
			/* handle error condiiton */
			return ia[_top --];
		}
	}
	void push(int value ) {
		if (full() ) {
			/* handle error condition */
			ia[++_top] = value; 
		}
	}
	bool peekback(int index, int & value) const;

private:
	int _top;
};

inline bool
	PeekbackStack::peekback(int index, int & value) const { 
		if (empty() ) {
			/* handle error condition */
		}
		if (index < 0 || index > _top) 
		{
			value = ia[_top];
			return false; 
		}
		value = ia[index];
		return true;
}
 

 

This is all good, except that there is a by-prpduct, whereas , Program using the new PeekbackStack class may also make inappropriate use of its IntArray base class public interface, for example. 

 

extern void swap(IntArray&, int, int);
Peekbackstack is(1024);

// oops: unexpected misuse of the PeekbackStack
swap(is, i , j);
is.sort();
is[0] = is[512];

So, the public inheritance represents a is-a relationship, while reflected back in our case, we can see that PeekbackStack is a special kind of IntArray, so you can expect that the operation that is applicable to PeekbackStack as well.  so we can see that public inheritance is not the best fit for our case, what we want to is to restrict the  user to the interfaces that is defined by us. 

 

So how to address that, here comes the private inheritance.  Let's see how we impl the private inheritance through the use of private inheritance

 

 

the solution is quite easy, you just change the public keyword with the private in the class derivation list. 

 

 

class PeekbackStack: private IntArray { ... }
 

 

as a side note, a private base class reflects a form of inheritance that is not based on subtype relationship. The entire public interface of the base class becomes private in the derived class. Each of the preceding misuses of a PeekbackStack class instance is now illegal except witin in friend and member functions of the derived class.

 

 

Thus, it may as well deserve to talk about composition versus inheritance as far as we have private inheritance covered.  

 

Since, after all with the private inheritance, we have achieved a kind of has-as relationship with regards to the IntArray classes. 

 

Here is the new PeekbackStack implementaion with Composition pattern .

 

 

class PeekbackStack 
{
private: 
	const int static bos = -1;
public:
	explicit PeekbackStack (int size):	stack (size), _top(bos) {}

	bool empty() const { return _top == bos; }
	bool full() const { return _top == stack.size() - 1; }
	int top() const { return _top; } 

	int pop() {
		if (empty() ) {
			 // handling error 
		}
		return stack[_top -- ];
	}

	void push(int value) 
	{
		if ( full() ) {
			// handle error condition
		}
		stack[++_top] = value; 
	}

	bool peekback(int index, int & value) const; 

private: 
	int _top;
	IntArray stack;
};

 

 

so you may wonder when to use private inheritance and when to use the composition by references/value?

 

so this is a very good guidelines as whether to use composition or private inheritance in a class design in  in which a has-a relationship exists

 

 

  • If we wish to override any of the virtual functions of a class, we must inherit from it privately.
  • If we wish to allow the class to refer to one of a hierarchy of possible types, we must use composition by reference
  • If as with our PeekbackStack class, we wish simply to reuse the implementation, composition by value is to be preferred over inheritance. If a lazy allocation of the object is desired, composition by reference (useing a pointer) is the generally preferred design choice. 

 

 

So we have covered the private and public inhertance, let's see why we have protected inheritance...

 

Before we introduce the protected inheritance, let's first examing the "exemping individual members"... since with private inhertiance, protected and public members are now all becomes private, in our example, you cannot allow the client to access the IntArray::size() method (which should be the same if the PeekbackStack class need to provide a size() method).

 

 

So what you can do is as follow.

class PeekbackStack : private IntArray
{
//....
public:
	
	// you can allow the client to access the IntArray size method by exempting the size method in the public section 
	using IntArray::size;

	// you can allow further subsequent derivation access to the protected members. you can exempt individual members in the protected section
protected: 
	using IntArray::_size;
	using IntArray::ia;
//....
};

 

However, this is tedious work and further, suppose that if we change the hierarchy so that 

 

Stack inherits IntArray, => PeekbackStack inherits Stack, if we were using the private inheritancfe, we cannot allow the PeekbackStack to override some members, while protected inheritaince provides a perfect balance/compromise. 

 

so if you do 

class Stack : protected IntArray { ... }

 then it you can easilty do 

class PeekbackStack : public Stack { ... } 
 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x ...

    Problem Solving with C++ (7th edition)

    - **Mixed-Type Expressions**: Discussion of type conversions that occur when performing arithmetic operations involving different data types. - **Common Bugs with = and ==**: Explanation of common ...

    C++ for Programmers

    The book features 240 C++ applications with over 15,000 lines of proven C++ code, and hundreds of tips that will help you build robust applications. Start with an introduction to C++ using an early ...

    Effective C++ 3rd en(with bookmarks)

    One of the most fundamental aspects of C++ highlighted in the book is the concept of viewing it not as a single monolithic language but as a federation of related sub-languages. This perspective is ...

    Sams Teach Yourself Visual C++ In 21 Days

    Learn Visual C++ through the Teach Yourself series, with sections on: Q&A, Do's and Don'ts, Workshop, Shaded syntax boxes, Type/Output/Analysis icons. Week One starts you with Visual C++. After ...

    深度探索C++对象模型 超清版

    指针的类型(The Type of a Pointer) 加上多态之后(Adding Polymorphism) 第2章 构造函数语意学(The Semantics of constructors) 2.1 Default Constructor的建构操作 “带有Default Constructor”的Member ...

    Exploring C++ 11

    Assuming no familiarity with C++, or any other C-based language, you’ll be taught everything you need to know in a logical progression of small lessons that you can work through as quickly or as ...

    C++超详细的基础教程

    Basics of C++ 1.C++程序结构 Structure of a program 2.变量和数据类型 Variables and Data types 3.常量 Constants 4.操作符/运算符 Operators 5.控制台交互 Communication through console 3.控制结构和...

    C++_CLI标准.pdf

    - **Type System Unification**: Section 8.2.4 discusses the unification of the type system in C++/CLI. - **Pointers, Handles, and Null**: Section 8.2.5 explores the use of pointers, handles, and null...

    C++14 Quick Syntax Reference 第2版

    This updated handy quick C++ 14 guide is a condensed code and syntax reference based on the newly updated C++ 14 release of the popular programming language. It presents the essential C++ syntax in a ...

    C++ 14 Quick Syntax Reference(2nd).pdf 2016第2版

    This updated handy quick C++ 14 guide is a condensed code and syntax reference based on the newly updated C++ 14 release of the popular programming language. It presents the essential C++ syntax in a ...

    Google C++ Style Guide_英文版.pdf

    Google recommends using the latest stable version of C++. At the time of this guide's publication, that would be C++17 or later. Keeping up-to-date with the language helps take advantage of new ...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    Based on the provided information from the file "Addison.Wesley.C++.by.Dissection.2002.pdf," we can derive a comprehensive overview of the C++ programming language as covered in this text. The book is...

    Effective C++(第三版)

    differentiate between inheritance of interface and inheritance of implementation. 条款35:考虑virtual函数以外的其他选择 consider alternatives to virtual functions. 条款36:绝不重新定义继承而来的non-...

    Google C++编程规范中文版

    ### Google C++编程规范中文版知识点详述 #### 一、背景 Google C++编程规范是一份详尽的文档,旨在指导开发人员编写高质量、可维护的C++代码。这份文档由Google内部多位资深工程师共同制定,是C++开发者的重要...

    Google C++ Style Guide中文版

    类型转换在某些情况下是必要的,但应避免使用C风格的转换(如`(type)`),而是使用更安全的C++风格的转换。 - **流 (Streams)** 流(如`std::cout`和`std::cin`)提供了一种方便的方式来输入输出数据。使用流时...

    Google C++ Style Guide

    ##### Run-Time Type Information (RTTI)(运行时类型信息) - RTTI的使用及其局限性。 ##### Casting(类型转换) - 不同类型的转换规则和推荐做法。 ##### Streams(流) - 输入输出流的使用技巧。 ##### ...

    Google C++编程规范(pdf 英文)

    - **Use of const**:使用`const`关键字来表示不可修改的数据成员或函数参数。 - **Integer Types**:使用固定宽度整型(如`int32_t`)来确保跨平台的一致性。 - **64-bit Portability**:编写64位兼容的代码,确保...

Global site tag (gtag.js) - Google Analytics