C + + virtual functions

Source: Internet
Author: User

Default parameter values for virtual functions

If a virtual function is declared in the base class with a default variable value, the default variable value is always accepted from the base class template of the function when the function is called through a base class pointer.

The default value in the function derived class version does not work.

#include <iostream>classBox {Private :    protected :        DoubleLength =1.0; Doublewidth =1.0; DoubleHeigth =1.0;  Public: Box () {}; Box (DoubleLengthvalue,DoubleWidthvalue,Doubleheigthvalue) {Length=Lengthvalue; Width=Widthvalue; Heigth=Heigthvalue; }        voidShow_volume () {std::cout<<"Volume is"<< Volume () <<Std::endl; }                Virtual DoubleVolumeinti = -) {Std::cout<< I <<Std::endl; returnlength*width*Heigth; }};classCarton: PublicBox {Private :    protected :     Public: Carton () {}; Carton (DoubleLengthvalue,DoubleWidthvalue,Doubleheigthvalue): Box (Lengthvalue, Widthvalue, Heigthvalue) {}; DoubleVolumeinti = -)Override{std::cout<< I <<Std::endl; return 0.85*length*width*Heigth; }            };intMain () {Box abox{ -, -, +}; Carton acarton{ -, -, +}; Box* Pbox (&Acarton); Std::cout<<"Carton Volume is"<< Pbox->volume () <<Std::endl; return 0;}

$./virtual
50
Carton volume is 20400

objects that have virtual functions consume more bytes than objects that do not have virtual functions.

Pure virtual function

There is no virtual function defined in the base class, and the class containing the virtual function is called an abstract class.

C + + virtual functions

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.