c++

Page 302

286

8. Class Inheritance

8.1.1 Member Functions

Member functions of a derived class can not access the private part of a base class, although a derived class contains all members of the base class. For example, the function Pt2d :: draw() can not be de ned as void Pt2d::draw() const { // incorrect cout << x << " " << y // x is not accessible }

A member of a derived class that is inherited from the private part of a base class may be called an invisible member of the derived class. Thus an invisible member of a class can not be accessed by members or friends even of the same class. This is for information hiding, since otherwise a private member of a class could be accessed freely just by deriving a new class from it. However, the hidden member x of the derived class Pt2d is accessible through the public member function Pt :: draw() : void Pt2d::draw() const { // draw the point Pt::draw() // draw x coordinate by Pt's draw() cout << " " << y // draw y coordinate }

Note the class quali er Pt :: must be used to refer to a member function of class Pt:

8.1.2 Constructors and Destructors

In de ning the constructor of a derived class, the constructor of the base class must be called in the initializer list (like class object members see x5.6) if the base class has a constructor. For example, Pt2d::Pt2d(double a = 0, double b = 0): Pt(a), y(b) { }

It can also be de ned alternatively as Pt2d::Pt2d(double a = 0, double b = 0): Pt(a) { y = b }

But it can not be de ned as Pt2d::Pt2d(double a = 0, double b = 0) { Pt(a) y = b }

The third de nition is wrong since the construction of base class Pt is not put in the initializer list. A derived class constructor can specify initializers for its own members and immediate bases only. The construction of an object of a derived class starts from the base class, then the members, and then the derived class itself. Its destruction is in the opposite order: rst the derived class itself,


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.