C++ How to declare/initialize a constant in a class?

In summary, the conversation discusses ways to declare and initialize a const member in a class in C++. The first attempt results in an error due to attempting to initialize the data member in the class. The second attempt also results in an error due to multiple declarations. The third attempt results in an error because const members cannot be modified. The solution is to use the static keyword before the const member to make it belong to the class rather than specific instances. The conversation also mentions the use of initialisation lists and inline initialization as alternative ways to initialize const members.
  • #1
Mr Virtual
218
4

Homework Statement


I have my computer science exam today (in 2 hours). I want to know how to declare and initialize a const member in a class.

The Attempt at a Solution



I tried this:

_________________________________________________________________
class stu
{
const int a=10; // Error cannot initialize a data member here
};
--------------------------------------------------------------------------

Then I tried this:
_________________________________________________________________
class stu
{
const int a;
};

int stu::a=10; //Error : Multiple declaration of stu::a
--------------------------------------------------------------------------

Then this:
_________________________________________________________________
class stu
{
const int a;

stu() //constructor
{
a=10; //Error: Cannot modify a const member
}

};

--------------------------------------------------------------------------

Please help!

Thanks
Mr V
 
Physics news on Phys.org
  • #2
I am using Turbo C++ 3.01

Mr V
 
  • #3
IIRC, when you don't need external linkage you can do this:

class stu { static const int a=10; };

If you need external linkage (eg you're building a library that will be linked to other modules) you're safer with this form:

class stu { static const int a; };
const int stu::a=10;

...I think.
 
  • #4
You're just missing the 'static' keyword.

- Warren
 
  • #5
Thanks a lot! It works perfectly.
But I am a little confused as to why the keyword 'const' is preceded by 'static'. Can't I just create a const without making it a static? I am asking this because value of a const cannot be changed, then why do we need to make it a static?

Mr V
 
  • #6
You're just missing the 'static' keyword.

Yeah, I realized that. But can you explain why we need to make it a static here?
Is this to make the objects able to share the const.
Mr V
 
  • #7
A static member belongs to the class; it is shared among all instances of the class. A non-static member belongs to a specific instance.

- Warren
 
  • #8
One more question: if I declare a member function as 'static const' what does it mean? I know that since it is static, it is restricted to accept/access static data members only. But what effect does maknig it a 'const' have on it? Will it accept/access only const values?

Mr V
 
  • #9
Static and const mean two different things. Static members belong to the class, rather than specific instances of the class. Static data isn't necessarily constant, though. A constant member is one that is created with a specific value, and whose value cannot ever be changed.

- Warren
 
  • #10
Sure you are right. But does making a function constant restrict it to access only const members?

Mr V
 
  • #11
No. If a function is constant, then it returns something (perhaps an object) which cannot be changed by the caller. It doesn't matter what data the function uses to create its return value.

- Warren
 
  • #12
Oh!Oh! How did I forget that! I forgot that the datatype preceding function name specifies its return type. So, if I declare a function const, it will return a const value.

Thanks a lot to you, and 'out of whack' for all your help. I hope I would fare well in my exam. Bye then!

Mr V
 
  • #13
Good luck!

- Warren
 
  • #14
Thanks!
I performed well. Only forgot that 'setw' is in 'iomanip.h' and that puts() automatically includes a newline character at the end of a string.
 
  • #15
I have my chemistry paper next, and I have a terrible confusion in Henry's law of solubility. I am creating the thread in the homework section (chemistry). Please help me there...:smile:

Mr V
 
  • #16
Mr Virtual,

Those things don't matter anyway. No one uses puts(). I'm almost amazed teachers test on such useless things!

- Warren
 
  • #17
It matters for me, because there was a question in which we had to write the output of a program, and there was a puts() function in it 8 times, which means there should be 8 lines in the output. But since I forgot this, I wrote the whole output in one line.
 
  • #18
I have just put up the chemistry thread. Please have a look at it...

Mr V
 
  • #19
Just a note Mr Virtual, please don't advertise one thread in another. Just make a new thread and let people read it as they will.

- Warren
 
  • #20
Right. I will keep that in mind.

Mr V
 
  • #21
Apart from using static which may not always be desired you can initialise a const variable in a class by doing the following:

Code:
class A
{
	const int aaa;
	A();
};

A::A()
{
	aaa(50); // init the const int aaa to the value 50
}
 
  • #22
But with that approach you can't use it as easily outside the class.
With static you can do, "A::aaa" anywhere without a 'A' class being instantiated, so you could have a class math with various constants and use "math::pi" in an equation.

Also it's safer to use an initialisation list if you are going to assing consts in a ctor.
 
  • #23
All here are forgot about Variable Initialization List Option on Constructor. Its used to Initialize the constant on the time of object creation and independent to class the constant can be initialized depend to object

class A
{
const int aaa;
A(int);
};

A::A(int paaa):aaa(paaa)
{
// Code For Construction
}
 
  • #24
Try inline initialization ...


class sample
{
const int i;

public:
sample():i(10)
{
}

};



njoy!
 
Last edited:
  • #25
#include<iostream>
using namespace std; class abc{
public:

// constructor
abc( const int);private:
const int SIZE ; // a private const int member, which u can initialize by base member initialization method

};

// can be done within constructor only
abc::abc(const int s):SIZE(s){ // so user entered value is initialize in const int
return;

}

int main(){


int inpt ;
cout << " enter input: " ;
cin >> input;

sam d(input);

cout << input ;



return 0;
}
 
  • #26
Sorry for bringing this one up,

but hey; at least I used search function, right?

My problem is similar: I have to set up a few mathematical classes... One should be "Ring" and one should be "Rational". Rational inherits from Ring.
Code:
class Rational : public Ring {...};
Ring is an abstract class, a Rational object looks like this:

Code:
int numerator_;
int denominator_;

Now: Every Ring has a neutral element, let's call it "n". Neutral means this: a + n = a, as example the natural numbers are a Ring, 0 is the neutral element(for addition, it would be 1 if the operation was multiplication). The neutral element in Rational is 0/1. I need to define these class constants...

so, a class constant Ring::zero shall represent the neutral element.

I hope you understand my problem, where should I put the declaration and definition of my constants.
 

1. How do you declare a constant in a class in C++?

To declare a constant in a class in C++, you can use the const keyword before the variable type in the class member declaration. For example: const int MAX_VALUE = 100;

2. Can you declare a constant in a class without initializing it?

Yes, you can declare a constant in a class without initializing it. However, you must initialize it in the class constructor or in the member initialization list.

3. How do you initialize a constant in a class in C++?

You can initialize a constant in a class in C++ either in the class constructor or in the member initialization list. For example: MyClass::MyClass() : MY_CONSTANT(10) { }

4. Can you change the value of a constant in a class in C++?

No, you cannot change the value of a constant in a class in C++. Constants, by definition, are immutable and cannot be modified after they are initialized.

5. Can you declare and initialize a constant in a single line in a class in C++?

Yes, you can declare and initialize a constant in a single line in a class in C++ using the constexpr keyword. For example: constexpr int MAX_VALUE = 100; This will make the constant a compile-time constant and it can be used in contexts that require compile-time constants.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
937
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
1K
  • Programming and Computer Science
2
Replies
35
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
1K
  • Programming and Computer Science
Replies
23
Views
2K
  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
2
Replies
36
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
Back
Top