The function and introduction of C ++ virtual method

When we use polymorphic public inheritance, we often use virtual methods. Adding virtual functions in front of member functions is called virtual functions . We define the method of the base class in the derived class. When we derive the object of the class, we also want to use this method name. At this time, if you use virtual functions, the program will choose the method version for the object type instead of the reference or pointer type.

class Brass
{
private:
    std::string fullName;
    long acctNum;
    double balance;
public:
    Brass(const std::string & s = "Nullbody", long an = -1,
                double bal = 0.0);
    void Deposit(double amt);
    virtual void Withdraw(double amt);
    double Balance() const;
    virtual void ViewAcct() const;
    virtual ~Brass() {}
};

//Brass Plus Account Class
class BrassPlus : public Brass
{
private:
    double maxLoan;
    double rate;
    double owesBank;
public:
    BrassPlus(const std::string & s = "Nullbody", long an = -1,
            double bal = 0.0, double ml = 500,
            double r = 0.11125);
    BrassPlus(const Brass & ba, double ml = 500, 
		                        double r = 0.11125);
    BrassPlus(const Brass & ba, double ml = 500, 
		                        double r = 0.11125);
    virtual void ViewAcct()const;
    virtual void Withdraw(double amt);
    void ResetMax(double m) { maxLoan = m; }
    void ResetRate(double r) { rate = r; };
    void ResetOwes() { owesBank = 0; }
};
		                     
		         

Among them, withdraw and ViewAcct are virtual functions, including destructors. When we use Brass to define an object dom and a derived class object to define an object dot

Brass dom("Dominc Banker",11224,413);
BrassPlus dot("Dominc Tanker",11211,429);
Brass &b1_ref=dom;
Brass &b2_ref=dot;
b1_ref.ViewAcct();//这里用的基类的ViewAcct
b2_ref.ViewAcct();//这里用的派生类的ViewAcct

If virtual is not added, then b2_ref.ViewAcct () uses the method of the base class, because the program selects the method according to the reference type and pointer type.
The problem of virtual functions satisfying polymorphism is that we want to manage both the base class and the derived class objects. We define an array of pointers to the base class, but when these pointers are assigned, they contain a pointer to the base class object and a pointer to the derived class object. Pointer. This achieves the purpose of polymorphic management.
The constructor cannot be a virtual function, the destructor should be a virtual function, and the friend function cannot be a virtual function.

Published 9 original articles · liked 0 · visits 253

Guess you like

Origin blog.csdn.net/a_465240/article/details/104817515