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

  • Context: Comp Sci 
  • Thread starter Thread starter Mr Virtual
  • Start date Start date
  • Tags Tags
    C++ Class Constant
Click For Summary

Discussion Overview

The discussion revolves around how to declare and initialize constant members in a C++ class. It includes various approaches, challenges faced by participants, and clarifications regarding the use of the 'static' keyword and the implications of declaring members as 'const'.

Discussion Character

  • Homework-related
  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant shares their attempts to declare and initialize a const member in a class, highlighting errors encountered in each approach.
  • Another participant suggests using 'static const' for class members, explaining the difference between static and non-static members.
  • There is a question about the necessity of the 'static' keyword when declaring const members, with some participants seeking clarification on its purpose.
  • A participant inquires about the implications of declaring a member function as 'static const' and how it affects access to member variables.
  • Several participants discuss the use of initialization lists in constructors for const members and the advantages of static members for accessibility without instantiating the class.
  • Another participant introduces the concept of inline initialization for const members within constructors.
  • A new participant raises a related question about defining class constants in an abstract class and their implementation in derived classes.

Areas of Agreement / Disagreement

Participants express varying opinions on the necessity and implications of using 'static' with const members, indicating that multiple competing views remain. The discussion does not reach a consensus on the best practices for declaring and initializing const members in classes.

Contextual Notes

Some approaches discussed may depend on specific compiler behaviors or versions of C++, and there are unresolved questions regarding the best practices for initializing const members in different contexts.

Who May Find This Useful

Students preparing for computer science exams, programmers looking for clarification on C++ class member declarations, and those interested in best practices for using const and static keywords in C++.

Mr Virtual
Messages
218
Reaction score
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
I am using Turbo C++ 3.01

Mr V
 
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.
 
You're just missing the 'static' keyword.

- Warren
 
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
 
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
 
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
 
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
 
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 ;
count << " enter input: " ;
cin >> input;

sam d(input);

count << 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.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 23 ·
Replies
23
Views
9K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 5 ·
Replies
5
Views
2K