Programming and Graphics

(Kiana) #1

190 Introduction to C++ Programming and Graphics


To make matters worse, we endow the rose class with the function:

void rose::printrtype() const
{
cout << "Rose type: "<< rosetype << endl;
}

and issue the statement:


pointer2 -> printrtype();

only to be greeted with the compiler error:


’class flower has no member named printrtype’

In contrast, the statement


pointer1 -> printrtype();

is perfectly acceptable. Thus, if a flower pointer is issued for a rose, use of this
pointer deprives us from using exclusive rose functions.


Virtual functions


A derived class inherits all parental functions. Can a derived class also
define, implement, and ultimately override parental functions? The answer is
affirmative, thanks to the concept of virtual functions.


In our example, we include in the public section of the flower class the
virtual functionprintrtypeimplementation:


virtual void printrtype() const{};

which renders the statement:


pointer2 -> printrtype();

perfectly acceptable. Becausepointer2points to a rose, when this statement
is executed, the functionprintrtypeof the rose class is invoked. Note that
we have entered nothing inside the curly brackets of the flower class function
printrtype, thus rendering this function idle. Alternatively, we could have
stated:


virtual void printrtype() const =0;
Free download pdf