Write a C++ Program to calculate Volume of Cube using constructor and destructor.input and outputSide length of the cube: 3Volume of the cube with side length 3 units is: 27 cubic units
Question
Write a C++ Program to calculate Volume of Cube using constructor and destructor.input and outputSide length of the cube: 3Volume of the cube with side length 3 units is: 27 cubic units
Solution
Sure, here is a simple C++ program that calculates the volume of a cube using constructor and destructor.
#include<iostream>
using namespace std;
class Cube {
private:
int side;
public:
// Constructor
Cube(int s) {
side = s;
}
// Function to calculate volume
int volume() {
return side * side * side;
}
// Destructor
~Cube() {
cout << "Destructor called!" << endl;
}
};
int main() {
int side;
cout << "Side length of the cube: ";
cin >> side;
// Create object of Cube
Cube c(side);
// Calculate and display volume
cout << "Volume of the cube with side length " << side << " units is: " << c.volume() << " cubic units" << endl;
return 0;
}
In this program, we have a class Cube with a private member side. The constructor Cube(int s) is used to initialize side with the value passed when an object of Cube is created. The volume() function calculates and returns the volume of the cube. The destructor ~Cube() is called automatically when the object is destroyed. It doesn't do anything in this program, but it's included to demonstrate how a destructor works.
Similar Questions
A cube has a surface area of 47,526 square units. What is the volume, in cubic units, of the cube?
The volume of a cube is represented by the expression below, where s is the side length of the cube.Find the volume of a plastic cube building block with a side length of 9 centimeters. A. 729 cubic centimeters B. 810 cubic centimeters C. 243 cubic centimeters D. 432 cubic centimetersReset Sub
The volume of a cuboid is 21 cubic units. Its length, width and height are all different positiveintegers. The sum of its length, width and height is:
A rectangular prism with a volume of cubic units is filled with cubes with side lengths of unit.How many unit cubes does it take to fill the prism?
Ver en españolBarry has two cubes of different sizes. The first cube has a volume of 1 cubic unit. The second cube has sides one-third as long as the first cube does. What is the volume of the second cube?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.