Explanation of pure virtual functions and abstract classes in C ++

Source: Internet
Author: User

Pure virtual functions are functions that do not need to be defined in the base class but must be overwritten in the derived class. The novelty "= 0" syntax can be used to declare a virtual function as a pure virtual function. For example:

Class base {
Public:
Void F1 (); // not a virtual function
Virtual void F2 (); // virtual function, but not pure virtual function
Virtual void F3 () = 0; // pure virtual function
};

Base B; // error: pure virtual F3 not overridden

Here, base is an abstract class (because it has a pure virtual function), so it cannot be used to define objects directly: Base (obviously) is used for base classes. For example:

Class derived: public base {
// F1 is not defined: It doesn't matter.
// F2 is not defined. It doesn't matter. It inherits base: F2.
Void F3 ();
};

Derived D; // OK: derived: F3 overwrites base: F3

Abstract classes are a good tool for defining interfaces. In fact, a class with only pure virtual functions is usually called an interface.

Of course, you can also define pure virtual functions:

Base: F3 (){}

This is often of little significance (although it provides some simple public code for the derived class), and the base: F3 () needs to be overwritten in the derived class ().

If you do not overwrite a pure virtual function in a derived class, the derived class is also an abstract class:

Class D2: public base {
// F1 is not defined: It doesn't matter.
// F2 is not defined. It doesn't matter. It inherits base: F2.
// F3 is not defined: It doesn't matter, but D2 is also an abstract class.
};

D2 D; // error: the pure virtual function base: F3 is not overwritten.

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.