C++ Code Example: volume of a cube

In this code example, the volume of a cube is calculated. First, a class named Cube is created. The class function getVolume() performs the actual calculation. The setVolume() function initializes the variables with values. Finally, objects of the class Rectangle are created. The class function setVolume() is called via these objects.

#include <iostream>
using namespace std;

class Cube {
    private:
        int length, width, height;
    public:
        void setVolume(int a, int b, int c) {
            length = a;
            width = b;
            height = c;
        }

        int getVolume() {
            return length * width * height;
        }
};

int main() {
    Cube c1, c2;

    c1.setVolume(1, 2, 6);
    c2.setVolume(2, 3, 6);

    cout << c1.getVolume() << endl;
    cout << c2.getVolume() << endl;

    return 0;
}

Explanation

Defining the Cube Class

Class Declaration

class Cube {
    private:
        int length, width, height;

The Cube class is declared with three private member variables: length, width, and height. These variables are encapsulated to restrict direct access from outside the class.

Member Functions

Setting Volume
public:
    void setVolume(int a, int b, int c) {
        length = a;
        width = b;
        height = c;
    }

The setVolume function is a public member function that sets the dimensions of the cube by assigning values to length, width, and height based on the provided parameters a, b, and c.

Calculating Volume
int getVolume() {
    return length * width * height;
}

The getVolume function is a public member function that calculates and returns the volume of the cube by multiplying its length, width, and height.

Main Function

Object Creation

int main() {
    Cube c1, c2;

Two objects, c1 and c2, of the Cube class are instantiated.

Setting Dimensions

c1.setVolume(1, 2, 6);
c2.setVolume(2, 3, 6);

The dimensions for c1 and c2 are set using the setVolume function, with c1 being set to 1x2x6 and c2 to 2x3x6.

Printing Volumes

cout << c1.getVolume() << endl;
cout << c2.getVolume() << endl;

The getVolume function is called on both c1 and c2, and their volumes are printed to the console.

Expected Output

The code will produce the following output:

12
36

Explanation:

  • Cube c1:
    Volume is 1×2×6=121×2×6=12
  • Cube c2:
    Volume is 2×3×6=362×3×6=36