ashim
ashim

Reputation: 25560

c++ constant variable defined by user

My program uses number PI. It should be constant value const double PI = 3.14. I want that user of the program could define this constants during Initialization of the class. For example, one of them want 3.14 and another 3.1416926. And after definition it should be constant value, i.e. during program nobody can change it. How can I implement it?

Upvotes: 1

Views: 239

Answers (2)

Software_Designer
Software_Designer

Reputation: 8587

Put const double PI = 3.141592653589793238462643383279502884197169399375105820974944 in a .h header file and include it in the .cpp file. Or you will get that error.

pi.h

const double PI = 3.141592653589793238462643383279502884197169399375105820974944;

Pi.cpp

#include <iostream>
#include "pi.h"
using namespace std;

class  Pi_Class
{
        public:

        double m_PI;

        Pi_Class()
        {
                     cout<<PI<<" \n";
        }

        Pi_Class(double fPI )
        {
            m_PI=fPI; 
                    cout<<m_PI<<" \n";
        }
};


int main()
{

   Pi_Class Pi_one(3.141);
   Pi_Class Pi_two(3.1415926535);
   Pi_Class Pi_thr(3.141592653589793238462643383279502884197169399375105820974944 );

    return 0;
}

Upvotes: -1

Greg Hewgill
Greg Hewgill

Reputation: 993015

You can create a per-instance constant using a constant member:

class MyClass {
    MyClass(double pi): PI(pi) { ... }
    const double PI;
};

Each object creator my specify a value of PI to use, which is constant for the lifetime of that object:

MyClass obj1(3.14);
MyClass obj2(3.1416926);

Upvotes: 6

Related Questions