C++ pure virtual functions (abstract classes)
Pure virtual functions are similar to abstract classes in JAVA
If the parent class has a pure virtual function, it cannot be instantiated if it does not implement the function when the subclass inherits
Pure virtual functions are not implemented:
#include <iostream>
/** * C++ pure virtual functions (abstract classes) */
using namespace std;
class Shape {
public:
Shape();
~Shape();
virtual double calcArea(a);
virtual void test(a)=0;
};
class Circle : Shape {
public:
Circle(int r);
~Circle();
protected:
int m_r;
};
Circle::Circle(int r) {
m_r = r;
}
Circle::~Circle() {
}
Shape::Shape() {
}
Shape::~Shape() {
}
double Shape::calcArea() {
}
int main(a) {
// A pure virtual function
Circle circle(2); // A pure virtual function is not implemented
return 0;
}
Copy the code
Implement pure virtual functions
#include <iostream>
/** * C++ pure virtual functions (abstract classes) */
using namespace std;
class Shape {
public:
Shape();
~Shape();
virtual double calcArea(a);
virtual void test(a)=0;
};
class Circle : Shape {
public:
Circle(int r);
~Circle();
virtual void test(a);
protected:
int m_r;
};
Circle::Circle(int r) {
m_r = r;
}
Circle::~Circle() {
}
void Circle::test() {
cout << "test()" << endl;
}
Shape::Shape() {
}
Shape::~Shape() {
}
double Shape::calcArea() {
}
int main(a) {
// A pure virtual function
Circle circle(2); // Implement pure virtual function after compiler execution pass
return 0;
}
Copy the code