HP C/aC++ for PA-RISC Software manual Class Base Virtual void f Must have a virtual function to

Models: C/aC++ for PA-RISC Software

1 230
Download 230 pages 50.97 Kb
Page 147
Image 147

// Define function from Base.

}

int main ()

{

Base *p;

//Code which does either

//p = new Base; or

//p = new Derived;

//Note that this is NOT a good design for this

//functionality Virtual functions would be better.

if (typeid(*p) == typeid(Base)) cout << “Base Object\n”;

else if (typeid(*p) == typeid(Derived)) cout << “Derived Object\n”;

else

cout << “Another Kind of Object\n”;

}

If a typeid operation is performed on an expression that is not a polymorphic type (a class which declares or inherits a virtual function), the operation returns the static (compile-time) type of the expression. In the example above, if class Base did not include the virtual function f, typeid(p) would always yield the type Base. The style of programming used in the above example is called a typeid switch statement. It is not recommended. One alternative is to use a virtual function in a base class specialized in each of its derived classes. In some cases, this may not be possible, for example, when the base class is provided by a library for which source code is not available. In other cases it may not be desirable, for example, some base class interfaces might be too big if all derived class functionality is included.

You can rewrite the previous example, using virtual functions, as:

class Base {

virtual void outputType() { cout << “Base Object\n”; }

// additional class details omitted

};

class Derived : public Base {

virtual void outputType() { cout << “Derived Object\n”; }

//additional class details omitted

};

int main ()

{

Base *p;

//code which does either

//p = new Base; or

//p = new Derived;

p->outputType();

}

A second alternative is to use a dynamic cast. In many cases, this alternative is less desirable than using virtual functions, but it is better than a typeid switch statement in nearly every case. There is a subtle difference between this alternative and the typeid switch statement above. The typeid operation allows access to the exact type of an object; a dynamic cast returns a non-zero result for the target type or a type publicly derived from it.

You can rewrite the previous example as follows using dynamic casts:

class Base {

 

virtual void f();

// Must have a virtual function to

HP aC++ Keywords 147

Page 147
Image 147
HP C/aC++ for PA-RISC Software manual Class Base Virtual void f Must have a virtual function to