Virtual Function Assignment Help

Assignment Help: >> Polymorphism - Virtual Function

Virtual Function

A virtual function is one which does not actually exist but it appears real in a few parts of a program.

A Virtual functions are advanced characteristics of the object oriented programming concept and they are not must for every C++ program.

The common form of virtual function is

Class user_defined_name

{

private:

---------------

---------------

public:

};

virtual return_type function_name(argruments);

virtual return_type function_name(argruments);

virtual return_type function_name(argruments);

----------------

To make a member virtual, the key term virtual is used in the methods although it is declared in the class definition but not in the member function definition.     The keyword virtual should be preceded through a return type of the function name.   The compiler obtains information from the keyboard virtual in which it is a virtual functions and not a conventional function declaration.

Example:

Class Sample

{

private:

int x;

int y;

public:

};

virtual void display ( );

virtual int sum (  );

1.   The key term virtual should not be repeated in the definition if the definition occurs outside the class declaration

2.   A virtual function cannot be a static member because a virtual member is always a member of a particular object in a class but a member of the class as a whole.

3.   It cannot have a constructor member function rather it could have the destructor member functions

4.   A destructor member function does not take any argument and no return type can be specified for it not even void

5.   It is an error to redefine a virtual method with a change of return data type in the derived class with the similar parameter types as those of a virtual method in the base class.

6.   Just a member function of a class could be declared as virtual.  That is an error to declare a non member function of a class virtual.

// virtual function demonstration

// array of pointers

# include<iostream.h>

class baseA

{

public:

virtual void display ( ){

cout<< "one\n";

}

};

class derivedB : public baseA

{

public:

virtual void display ( )

{

cout<<"two\n";

}

};

class derived C : public derivedB

{

public:

virtual void display ( )

{

cout<<"three \n";

}

};

void main( )

{

baseA obja;

 derivedB objb;

derivedC objc; baseA *ptr[3];

ptr[0] = &obja;

ptr[1] = &objb;

ptr[2] = &objc;

for(int i = 0; i <= 2; i++)

ptr[ i ] -> display ( );

}

output of the program is

one

two

three

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd