Virtual destructor (√), pure virtual destructor (√), virtual constructor (X)

Source: Internet
Author: User
Tags define abstract

from:http://blog.csdn.net/fisher_jiang/article/details/2477577

A. Virtual destructor

We know that in order to be able to correctly invoke the destructor of an object, it is generally required that a top-level class with a hierarchy define its destructor as a virtual function. Because when you delete an abstract class pointer, you must find the real destructor through the virtual function.

Such as:

Class Base
{
Public
Base (){}
Virtual ~base (){}
};

Class Derived:public Base
{
Public
Derived (){};
~derived (){};
}

void Foo ()
{
Base *PB;
PB = new Derived;
Delete PB;

This is the correct usage, and the dynamic binding will occur, it will call the derived destructor first, then the destructor of base

If the destructor does not add Virtual,delete PB only executes the destructor of the base, not the true derived destructor.
Because it is not a virtual function, the function that is called depends on the static type, which is the base

Two. Pure virtual destructor
The problem is that we want to make base an abstract class that cannot directly construct an object and need to define a pure virtual function in it. If there are no other suitable functions, the destructor can be defined as pure virtual, and the preceding CObject definition will be changed to:

Class Base
{
Public
Base (){}
Virtual ~base () = 0
};However, this code cannot be compiled, usually a link error, and cannot find a reference to the ~base () (GCC error report). This is because destructors, constructors, and other intrinsic functions are different, and when called, the compiler needs to produce a call chain. That is, the destructor of base is implicitly called in the derived destructors. In the code just now, the missing function body of ~base () will, of course, be wrong.

There is a misunderstanding, some people think, Virtual F () =0 this pure virtual function syntax is not defined by the semantics of the body.
In fact, this is not right. This syntax simply indicates that the function is a pure virtual function, so this class becomes an abstract class and cannot produce an object. We You can specify a function body for a pure virtual function entirely . the usual pure virtual function does not require the function body, because we generally do not invoke this function of the abstract class, only the corresponding function of the derived class is called. Thus, we have a pure virtual destructor function body, the above code needs to be changed to:
Class Base
{
Public
Base ()
{
}
Virtual ~base () = 0; Pure virtual
};

Base::~base ()//function body
{

From a syntactic point of view, the above destructors cannot be written directly to the class declaration (the method of inline functions). This may be a non-orthogonal place. But it does seem a little cumbersome.

This problem seems to be somewhat scholarly, because in general we can find a more suitable function in base, by defining it as a pure virtual function without implementing a body, and defining an entire class as an abstract class. But this technique also has some applications, such as this example:

Class Base//abstract Class
{
Public
Virtual ~base (){};//virtual, not pure
virtual void Hiberarchy () const = 0;//pure virtual
};

void Base::hiberarchy () const//pure Virtual also can have function body
{
   std::cout << "Base::hiberarchy";
}

Class derived : public base
{
Public:
   derived () {}
   virtual void  Hiberarchy ()  const
   {
        cb::hiberarchy ();
       std::cout << "Derived::hiberarchy";
   }
   virtual void foo () {}
};


Int main () {
   base* pb=new derived ();
   pb->hiberarchy ();
   pb->base::hiberarchy ();
   return 0;

In this example, we try to print out the inheritance relationship of the class. The virtual function hiberarchy is defined in the base class and is then overloaded in each derived class. Once again we see that because we want to make base an abstract class, and no other suitable method member in this class can be defined as pure virtual, we still have to define hiberarchy as pure virtual. (Of course, you can definitely define the ~base function, which is the same as the discussion above.) ^_^)

In addition, it can be seen that in main there are two methods of invocation, the first is the normal way, dynamic link, execute virtual function, get the result "Derived::hiberarchy", the second is to specify the way of the class, the virtual function will no longer perform the dynamic link process, the result is "Base:: Hiberarchy ".

As can be seen from the above analysis,The real purpose of defining pure virtual functions is to define abstract classes, not the function itself. In contrast, in Java, the syntax for defining an abstract class is abstract class, which is specified at the level of the class (of course, virtual functions are also added with the abstract keyword). Isn't this the better way? In Stroustrup's "C + + language design and evolution" I found such a passage:

"I chose to describe individual functions as pure virtual, not in the form of defining a complete class declaration as abstract, because the concept of pure virtual functions is more flexible. I value the ability to define classes in stages, that is to say, I find it useful to define some pure virtual functions in advance, and to define other classes for further derivation. "

I have not fully understood the latter sentence, and I would like to elaborate on this concept from another perspective. That is, in a multi-layered complex class structure, the intermediate-level classes should materialize some abstract functions, but probably not all of them. The middle class does not need to know whether to materialize all the virtual functions, and what functions their ancestors have materialized, as long as they focus on their duties. In other words, the middle class does not need to know whether it is a real abstract class, and the designer does not have to consider whether it is necessary to add an abstract-like description at the class level of this intermediate class.

Of course, the design of a language has a variety of factors, good or bad are all aspects. It's just an explanation.

Finally, some common questions about virtual functions are summarized:

1) Virtual functions are dynamically bound, that is, pointers and references that use virtual functions can correctly locate the corresponding function of the actual class, rather than executing the function that defines the class. This is the basic function of the virtual function, it is no longer explained.

2)constructor cannot be a virtual function。 Andcalling a virtual function in a constructor, actually executing the corresponding function of the parent class, because they have not been constructed well, polymorphism is disable.

3)Destructors can be virtual functions, and, in a complex class structure, this is often necessary.

4) Defining a function as a pure virtual function is actually defining the class as an abstract class and cannot instantiate an object.

5)pure virtual functions usually have no defined body, but they can also be fully。

6) Destructors can be purely virtual, buta pure virtual destructor must have a defined body, because the invocation of the destructor is implied in the subclass.

7) A non-pure virtual function must have a defined body, or it is an error.

8) The Override virtual function definition of a derived class must be exactly the same as the parent class.In addition to a special case, if the return value in the parent class is a pointer or reference, the subclass override can return the derivation of this pointer (or reference)。 For example, in the example above, virtual base* clone () is defined in Base; Virtual derived* clone () can be defined in Derived. As you can see, this relaxation is very useful for the clone pattern.
Other, needs to be supplemented.

Virtual destructor (√), pure virtual destructor (√), virtual constructor (X)

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.