const member variables in a class...

S

sam_cit

Hi Everyone,

When a variable is declared as const, it is initialized along with
the declaration, as modification later on is not possible.
Having seen that, how about const variables in a class? Is it possible
for a class to have const variables? As just declaring the class alone
doesn't create any memory, only creation of objects results in memory
allocation for the object.

Thanks in advance!!!
 
B

Bart Simpson

Hi Everyone,

When a variable is declared as const, it is initialized along with
the declaration, as modification later on is not possible.
Having seen that, how about const variables in a class? Is it possible
for a class to have const variables? As just declaring the class alone
doesn't create any memory, only creation of objects results in memory
allocation for the object.

Thanks in advance!!!

Yes its possible for classes to have const member variables. You must
initialize them in an initialization list however.
 
S

sam_cit

Yes its possible for classes to have const member variables. You must
initialize them in an initialization list however.

Can you show an example of how it is done?
'
Thanks in advance!!!
 
S

Salt_Peter

Can you show an example of how it is done?
'
Thanks in advance!!!

#include <iostream>

class A
{
const int m_n;
public:
A();
int get() const;
};

// def ctor with init list
A::A() : m_n( 99 )
{
}

int A::get() const
{
return m_n;
}

int main()
{
A a;
std::cout << a.get() << std::endl;
}

/*
99
*/

//// also:

class A
{
...
public:
A(int n);
...
};

// def parametized ctor with init list
A::A( int n = 99 ) : m_n( n )
{
}

int main()
{
A a;
std::cout << a.get() << std::endl;
A another(88);
std::cout << another.get() << std::endl;
}

/*
99
88
*/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,303
Latest member
Ketonara

Latest Threads

Top