Abstract base classes and pure imaginary numbers

catalogue

 

Abstract base classes and pure imaginary numbers

Relationship between abstract base classes and pure imaginary numbers

The meaning of virtual function

Pure virtual function code example

Abstract base classes and pure imaginary numbers

Relationship between abstract base classes and pure imaginary numbers

A base class that cannot be instantiated is called an abstract base class. Such a base class has only one purpose, that is, to derive other classes from it. In C++, to create an abstract base class, you can declare pure virtual functions. As long as there are pure virtual functions in the class body, you cannot create an instance object of the class.

Although an abstract base class cannot be instantiated, the type of a pointer or reference can be specified as an abstract base class. Abstract base classes provide a very good mechanism for declaring functions that all derived classes must implement.

The meaning of virtual function

We usually encounter this situation:

We want to use the base class pointer to call the derived class object. If the base class member function is declared as a virtual function, we use the base class pointer to call the member function in the derived class to achieve more powerful functions. However, we must declare and define a function body of the same name with the virtual keyword in the base class. This is too troublesome. I don't want to define the function body, so I declare this base class member function as a pure virtual function.

Pure virtual function code example

#include <iostream>  
#include <string>  
using namespace std;  
  
class Cperson  
{  
protected:  
    float mark;  
    string name;  
public:  
    Cperson(string name, float mark)  
    {  
        this->name = name;  
        this->mark = mark;  
    }  
    ~Cperson()  
    {  
        cout << "call Cperson Destructor for" << endl;  
    }  
    virtual void ShowInf() = 0; //Pure virtual function declaration form
    //Pure virtual function has no function body defined and cannot allocate storage space, so the base class object cannot be defined
};  
  
class Cstudent:public Cperson  
{  
private:  
    char sex;  
public:  
    Cstudent(char sex, string name, float mark) :Cperson(name, mark)  
    {  
        this->sex = sex;  
    }  
    ~Cstudent()  
    {  
        cout << "call Cstudent Destructor" << endl;  
    }  
    void ShowInf()  
    {  
        cout << this->name << "Gender:" << this->sex << ";Score is" << this->mark << "branch" << endl;  
    }  
};  
  
//Calling a derived class object using a base class pointer
void ShowInf(Cperson *person)  
{  
    person->ShowInf();  
}  
  
int main()  
{  
    Cstudent stud('m', "Super bully", 99.99);  
    ShowInf(&stud);  
}

  

 

Tags: C++ Class Polymorphism pointer

Posted by Easter Bunny on Tue, 31 May 2022 18:49:33 +0530