Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Formulate the Math class so that it is not possible to create or make copies of

ID: 3918676 • Letter: F

Question

Formulate the Math class so that it is not possible to create or make copies of objects of the class Math.

#include<iostream>
using namespace std;

class Math
{
public:
static const double pi;
static const double root2;
};

const double Math::pi = 3.1416;
const double Math::root2 = 1.4142;

int main()
{
cout << "pi value : " << Math::pi << endl;
cout << "root2 value : " << Math::root2 << endl;


return 0;
}

I already tried the following two ways.

For the first one, my teacher said, "If it's correct, then it shouldn't be possible to create or make copies of objects of the Math class, but that's exactly what you did in the main function, so it's not correct." For the second one, he said, "It doesn't have anything to do with making the data members static or non-static." How can I fix it?

(1)

(2)

#include<iostream>
using namespace std;

class Math
{
public:
const double pi;
const double root2;
};

const double Math::pi = 3.1416;
const double Math::root2 = 1.4142;

int main()
{
cout << "pi value : " << Math::pi << endl;
cout << "root2 value : " << Math::root2 << endl;


return 0;
}

Explanation / Answer

#include <iostream>

using namespace std;

class Math

{

public:

const double pi;

const double root2;

private:

Math(); // Make the default constructor private, this prevents from creating objects

Math(const Math&); // Make the copy constructor private, this prevents from copying objects

};

const double Math::pi = 3.1416;

const double Math::root2 = 1.4142;

int main()

{

cout << "pi value : " << Math::pi << endl;

cout << "root2 value : " << Math::root2 << endl;

return 0;

}