[Turn]c++ virtual explanation

Source: Internet
Author: User

Virtual is a very important keyword in the C + + oo mechanism. As long as anyone who has studied C + + knows that a function that adds the virtual keyword to the class base is a dummy function (such as a function print), it is possible to override the virtual function by overriding it in the derived class derived of base. When the pointer point of base class base points to an object of the derived class derived, the call to the print function of a is actually called the print function of derived instead of base. This is the embodiment of polymorphism in object-oriented. (for how virtual mechanisms are implemented, see inside the C + + Object Model, Addison Wesley 1996)
Class Base
{
Public:base () {}
Public
virtual void print () {cout<< "Base";}
};

Class Derived:public Base
{
Public:derived () {}
Public
void print () {cout<< "Derived";}
};

int main ()
{
Base *point=new Derived ();
Point->print ();
}

Output:
Derived
This may be reminiscent of overloading the function, but a little contrast will reveal that the two are completely different:
(1) Several functions of overloading must be in the same class;
The overridden function must be in a different class that has an inheritance relationship
(2) Several functions covered must have the same function name, parameter and return value;
Overloaded functions must have the same function name and different parameters. The purpose of the parameter is to be able to use parameters to determine which function the program is calling when the function is called. It is also natural to explain why a function cannot be overloaded by a return value, because the program will probably not care about the return value when it calls the function, and the compiler cannot see from the code which function the program is calling.
(3) must add the keyword virtual before the function is overwritten;
Overloading and virtual do not have anything to do with it, and the addition does not affect the operation of overloading.

About the hidden rules for C + +:
I have heard about the hidden rules of C + +:
(1) If the function of the derived class has the same name as the function of the base class, but the parameters are different. At this point, whether or not virtual
keyword, the function of the base class is hidden (note that it is not confused with overloading).
(2) If a function of a derived class has the same name as a function of the base class and the parameters are the same, the base class function has no virtual
Key word. At this point, the function of the base class is hidden (be careful not to confuse the overlay).
#include <iostream.h>
Class Base
{
Public
virtual void F (float x) {cout << base::f (float) << x << Endl;}
void g (float x) {cout << base::g (float) << x << Endl;}
void h (float x) {cout << base::h (float) << x << Endl;}
};

Class Derived:public Base
{
Public
virtual void F (float x) {cout << derived::f (float) << x << Endl;}
void g (int x) {cout << "derived::g (int)" << x << Endl;}
void h (float x) {cout << derived::h (float) << x << Endl;}
};

void Main (void)
{
Derived D;
Base *PB = &d;
Derived *PD = &d;
Good:behavior depends solely on type of the object
Pb->f (3.14f); Derived::f (float) 3.14
Pd->f (3.14f); Derived::f (float) 3.14
Bad:behavior depends on type of the pointer
Pb->g (3.14f); Base::g (float) 3.14
Pd->g (3.14f); Derived::g (int) 3 (surprise!)
Bad:behavior depends on type of the pointer
Pb->h (3.14f); Base::h (float) 3.14 (surprise!)
Pd->h (3.14f); Derived::h (float) 3.14
}

BP and DP point to the same address, supposedly running results should be the same, and in fact the results of the operation is different, so he attributed the reason to the C + + hidden rules, in fact, this view is wrong. The decision to run the BP and DP call functions is not the address they point to, but their pointer type. "Polymorphism only works if you indirectly point to a derived class subtype through a base class pointer or reference" (C + + Primer 3rd Edition). PB is a base class pointer, PD is a pointer to a derived class, all function calls to PD are simply calls to their own functions, and polymorphism independent, so the results of all function calls of PD are output Derived:: is completely normal; PB function call if there is virtual, the derived class is called based on polymorphism. If no virtual is a normal static function call, or call the base class, so there is virtual F function call output derived::, the other two no virtual or output base:: Very normal Ah, nothing surprise!
So there is no so-called hidden rules, although the "high-quality C++/C Programming Guide" is a very good book, but we do not superstition oh. Remember that "polymorphism only works if you indirectly point to a derived class subtype through a base class pointer or reference."

Pure virtual function:
The C + + language provides us with a syntax structure that can be used to indicate that a virtual function simply provides an interface that can be overridden by a quilt type. However, it cannot be invoked by itself through a virtual mechanism. This is a purely virtual function (pure
virtual function). The declaration of a pure virtual function is as follows:
Class Query {
Public
declaring pure virtual functions
Virtual ostream& Print (ostream&=cout) const = 0;
// ...
};
Here the function declaration is immediately followed by the assignment value 0.
A class that contains (or inherits) one or more pure virtual functions is recognized by the compiler as an abstract base class. Attempting to create a standalone class object with an abstract base class can cause compile-time errors. (It's also a mistake to call a pure virtual function through a virtual mechanism, for example)
Query declares a pure virtual function
Therefore, the programmer cannot create a separate Query class object
Query sub-object in Ok:namequery
Query *PQ = new Namequery ("Nostromo");
Error: New expression assigned to Query object
Query *pq2 = new query;
Abstract base classes can only appear as child objects in subsequent derived classes.

If you only know that virtual is in front of the function, then only half of it is known to you, and one important usage of virtual is virtual public. Virtual inheritance is described in more detail in C + + primer, as explained in the following slightly modified way:
Inheritance in C + + is a special case of "combination by value" by default. When we write
Class Bear:public Zooanimal {...};
Each Bear class object contains all non-static data members of its Zooanimal base class sub-object and non-static data members declared in the bear similarly when the derived class itself also acts as a base class object such as:
Class Polarbear:public Bear {...};
The Polarbear class object contains all non-static data members declared in Polarbear and all non-static and Zooanimal child objects of all nonstatic data members and their bear child objects. This special form of combination of values, supported by inheritance, provides the most efficient and most compact representation of objects under single inheritance. Under multiple inheritance, when a base class appears multiple times in a derived hierarchy, the main practical example is the Iostream class hierarchy. The Ostream and IStream classes derive from the abstract iOS base class, and the Iostream class is derived from Ostream and IStream
Class iostream:p ublic IStream, public ostream {...};
By default, each Iostream class object contains two iOS child objects: an instance in the IStream child object and an instance in the Ostream child object. Why is this bad? In terms of efficiency, storing two copies of the iOS sub-object is a waste of storage because iostream only needs one instance. Also, the iOS constructor was called two times per child object at a time. The more serious problem is the two semantics caused by two instances. For example, any unqualified access to an iOS member will result in a compile-time error: which instance is accessed? What happens if Ostream and IStream have a slightly different initialization of their iOS child objects? How do I guarantee the consistency of this pair of iOS values through the iostream class? There is really no good way to guarantee this, under the default by-value combination mechanism.
The solution for the C + + language is to provide another alternative to the inheritance mechanism by "reference combination" virtual inheritance (virtual inheritance) under dummy inheritance, only one shared base class sub-object is inherited, regardless of the base class at the derived level
The number of times a shared base class child object is called a virtual base class.
By using the keyword virtual repair a declaration of a base class can be specified as being a virtual derivation. For example, the following declarations make Zooanimal a virtual base class for bear and raccoon:
Keywords Public and virtual
Order of not important
Class Bear:public virtual Zooanimal {...};
Class Raccoon:virtual public Zooanimal {...};
Virtual derivation is not an explicit attribute of the base class itself, but its relationship to derived classes, as described earlier, virtual inheritance provides a "combination by reference". In other words, access to child objects and their non-static members is indirect. This makes it possible to combine multiple virtual base class sub-objects into a shared instance of a derived class in multiple inheritance cases, providing the necessary flexibility. At the same time, even if a base class is virtual, we can still manipulate the object of the derived class through a pointer or reference to that base class type.


[Turn]c++ virtual explanation

Related Article

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.