Differences between virtual functions and pure virtual functions

Source: Internet
Author: User

Virtual functions are an important concept in Object-Oriented C ++. Because it fully embodies the inheritance and polymorphism features in object-oriented thinking, it is widely used in C ++. For example, in Microsoft's MFC class library, you will find that many functions have virtual keywords, that is, they are all virtual functions. It is no wonder that virtual functions are the essence of the C ++ language.

So what is a virtual function? Let's take a look at Microsoft's explanation:

A virtual function is a member function that you want to overload in a class. When you use a base class pointer or reference to point to an inherited class object, you call a virtual function, the actual version of the inherited class is called. 

-- From msdn

This definition is not very clear. An example is provided in msdn, but its example does not properly illustrate the problem. Let's write an example:

# Include "  Stdio. h  "  
# Include" Conio. h "

Class Parent
{
Public :
Char Data [ 20 ];
Void Function1 ();
Virtual Void Function2 (); // Function2 is a virtual function.
} Parent;

Void Parent: function1 ()
{
Printf ( " This is parent, function1 \ n " );
}

Void Parent: function2 ()
{
Printf ( " This is parent, function2 \ n " );
}

Class Child: Public Parent
{
Void Function1 ();
Void Function2 ();

} Child;

Void Child: function1 ()
{
Printf ( " This is child, function1 \ n " );
}

Void Child: function2 ()
{
Printf ( " This is child, function2 \ n " );
}

Int Main ( Int Argc, Char * Argv [])
{
Parent * P; // Define a base class pointer

If (_ Getch () = ' C ' ) // If you enter a lowercase letter C
P = & child; // Point to an inherited Class Object
Else
P = & parent; // Otherwise, it refers to the base class object.

P-> function1 (); // The entry address of parent: function1 () is provided during compilation.
P-> function2 (); // Note: Which function 2 is executed here?

Return 0 ;
}

Compile and run visual c ++ or Borland C ++ of any version, and enter a lower-case letter C to obtain the following results:

This is parent, function1
This is child, function2

Why is the result of the first line? Because we use a pointer to the parent class to call the function fuction1 (), although the pointer actually points to the Child class object, the compiler cannot know this fact (until running,ProgramCan be used to determine the object pointed to by the pointer according to the user input), it can only be understood and compiled by calling the parent class function, so we see the result of the first line.

So what is the result of the second line? We noticed that the function2 () function is modified by the virtual keyword in the base class, that is, it is a virtual function. The most important feature of a virtual function is "dynamic concatenation". It can judge the object pointed to by the pointer at runtime and automatically call the corresponding function. If we enter any non-C character when running the above program, the result is as follows:

This is parent, function1
This is parent, function2

Note that the result of the second line has changed. The program only calls a function2 () function, but it can automatically decide whether to call function2 in the base class or function2 in the inheritance class based on the user input. This is the role of the virtual function. We know that in MFC, many classes need to be inherited by you, and many of their member functions need to be overloaded. For example, the most commonly used cview for compiling MFC applications :: the ondraw (CDC *) function must be reloaded. Define it as a virtual function (in fact, in MFC, ondraw is not only a virtual function, but also a pure virtual function). It can ensure that ondraw compiled by the user is called at all times. The important use of virtual functions is evident here.
-----------------------------------------------------------
Let's look at the following
The concept of virtual functions and pure virtual functions in C ++ about the size of a derived class. Differences and causes

First, emphasize a concept.

Define a functionVirtual Functions, Does not mean that the function is not implemented, it is defined as a virtual function isTo allow the use of base class pointers to call this function of the subclass 
Define a functionPure virtual functionsIs definedTo implement an Interface,Plays a normative roleThe programmer who inherits this class must implement this function.
 

Impact on inheritance:
Ordinary Classes (without virtual functions, pure virtual functions) can be inherited and work quite well.

You have the following questions:
Is pure virtual functions designed to implement interfaces? What is the meaning of an interface?
Why should I pre-define it? In the future, it is hard to predict that a function will be used in my class one day. Isn't it possible to add a function?

Instantiate a class:
Classes with pure virtual functions cannot generate class objects. If they do not have pure virtual functions, they can. For example:

 Class CA
{
Public :
Virtual Void Fun () = 0 ;// The fun function is a pure virtual function.
Virtual Void Fun1 ();
};

Class CB
{
Public :
Virtual Void Fun ();
Virtual Void Fun1 ();
};

// Implementation of Ca and CB classes
...

Void Main ()
{
Ca;// No, because the class CA has pure virtual functions.
Cb B; // Yes, because class CB does not have pure virtual functions.

...
}

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

Use of virtual functions in the middle of polymorphism:
Polymorphism is generally implemented by pointing to the base class pointer.
Dog mydogwangwang;
Mydogwangwang. Born ();
It must be "dog"
So
Horse myhorsepipi;
Myhorsepipi. Born ();
It must be "horse"

Is it also polymorphism?
//////////////////////////////////////// /////////
One thing you must understand is to use the parent class pointer to call the subclass at runtime:
For example, a function is as follows:

 
VoidAnimal: fun1 (animal * maybedog_maybehorse)
{
Maybedog_maybehorse-> born ();
}

The maybedog_maybehorse parameter does not know whether it is a dog class or a horse class at the time of compilation. Therefore, it is set to an animal class. The function is used only when it is determined by the runtime.
That is to say, the parent class pointer is used to determine who the runtime is directed to through the virtual function.

//  Use virtual functions  
# Include <iostream. h>

Class Animal
{
Public :
Animal ();
~ Animal ();
Void Fun1 (animal * maybedog_maybehorse );
Virtual Void Born ();
};

Void Animal: fun1 (animal * maybedog_maybehorse)
{
Maybedog_maybehorse-> born ();
}

Animal: Animal ()
{
}
Animal ::~ Animal ()
{
}
Void Animal: Born ()
{
Cout <" Animal " ;
}
Class Dog: Public Animal
{
Public :
Dog ();
~ Dog ();
Virtual Void Born ();
};
Dog: Dog ()
{
}
Dog ::~ Dog ()
{
}
Void Dog: Born ()
{
Cout < " Dog " ;
}

Class Horse: Public Animal
{
Public :
Horse ();
~ Horse ();
Virtual Void Born ();
};

Horse: Horse ()
{
}
Horse ::~ Horse ()
{
}
Void Horse: Born ()
{
Cout < " Horse " ;
}

Void Main ()
{
Animal;
Dog B;
Horse C;
A. fun1 (& C );
}
// Output: Horse

// No virtual functions
# Include <iostream. h>

Class Animal
{
Public :
Animal ();
~ Animal ();
Void Fun1 (animal * maybedog_maybehorse );
Void Born ();
};

Void Animal: fun1 (animal * maybedog_maybehorse)
{
Maybedog_maybehorse-> born ();
}
Animal: Animal ()
{
}
Animal ::~ Animal ()
{
}
Void Animal: Born ()
{
Cout < " Animal " ;
}
Class Dog: Public Animal
{
Public :
Dog ();
~ Dog ();
Void Born ();
};

Dog: Dog ()
{
}
Dog ::~ Dog ()
{
}
Void Dog: Born ()
{
Cout < " Dog " ;
}
Class Horse: Public Animal
{
Public :
Horse ();
~ Horse ();
Void Born ();
};
Horse: Horse ()
{
}
Horse ::~ Horse ()
{
}
Void Horse: Born ()
{
Cout < " Horse " ;
}

Void Main ()
{
Animal;
Dog B;
Horse C;
A. fun1 (& C );
}
// Output: Animal

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

Classes with pure virtual functions are abstract classes. Objects cannot be generated and can only be derived. The pure virtual function of the derived class is not rewritten, so its derived class is still an abstract class..
---------------------------------------------------------------

The pure virtual function is defined to make the base class uninstantiated,
This is because instantiation of such abstract data structures is meaningless.
Or the implementation is meaningless.
In fact, I personally think that the introduction of pure virtual functions is for two purposes:

1. To ensure security, avoid any unknown results that need to be clarified but are accidentally caused. Remind the subclass to implement the implementation.
2. for efficiency, it is not for program execution efficiency, but for encoding efficiency.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.