Case Study: Implementing Inheritance in a Physics Engine
Here's an example of implementing inheritance in a simple physics engine using C++:
#include <iostream>
class Shape {
public:
virtual float getVolume() { return 0.0; }
};
class Cube : public Shape {
public:
Cube(float side) : sideLength(side) {}
float getVolume()
{ return sideLength * sideLength * sideLength; }
private:
float sideLength;
};
class Sphere : public Shape {
public:
Sphere(float radius) : r(radius) {}
float getVolume()
{ return (4.0 / 3.0) * 3.14159265358979323846 * r * r * r; }
private:
float r;
};
int main() {
Cube cube(5.0);
Sphere sphere(3.0);
Shape *shapes[2] = { &cube, &sphere };
for (int i = 0; i < 2; i++) {
std::cout << "Volume: "
<< shapes[i]->getVolume() << std::endl;
}
return 0;
}
The program starts with the line "#include <iostream>", which includes the input/output stream library, which is used for printing to the console.
The next line, "class Shape", defines a base class called "Shape", which represents a basic 3D shape. This class has a single virtual function called "getVolume()" that returns the volume of the shape. The "virtual" keyword makes the function virtual, which means it can be overridden by derived classes.
The next class, "class Cube", is a derived class from "Shape" that represents a cube. The keyword "public" in the class definition specifies that the class inherits the public members of the base class. The class has a constructor that takes a single float argument for the side length of the cube and a single member variable to store the side length. The class also overrides the "getVolume()" function to return the volume of the cube.
The next class, "class Sphere", is a derived class from "Shape" that represents a sphere. The class has a constructor that takes a single float argument for the radius of the sphere and a single member variable to store the radius. The class also overrides the "getVolume()" function to return the volume of the sphere.
In the main function, objects of the classes "Cube" and "Sphere" are created and stored in an array of Shape pointers. The function then iterates over the array and calls the "getVolume()" function on each element. Since the function is virtual, the correct implementation of the function is called for each object, whether it's a cube or a sphere.
Finally, the line "return 0;" is used to exit the main function and the program, indicating that it has completed successfully.
This is a basic example of how inheritance can be used in C++. By using inheritance, we can create a hierarchy of classes that share common properties and behavior, and we can easily extend the hierarchy by adding new derived classes. This makes the code more modular, reusable, and maintainable.