member const initialisation

S

santosh

Hello,
I have const member in the class.
How can I initialise these.
I can not initialise in constructor ,(it is giving compilation error)
What is the proper way to initialise.
The code is given below.
Regards,
santosh




class NamedPtr
{
const string a;
const int i;
const int* ptr_int;
public:
NamedPtr(const string &s,int * x,int b=90)
{
cout<<"constor"<<endl;
//=b;
//s;
//r_int=x;
}
 
M

Mike Wahler

santosh said:
Hello,
I have const member in the class.
How can I initialise these.

Do it the same way any member is initialized,
in the initializer list.
I can not initialise in constructor ,(it is giving compilation error)

Nothing can be initialized in the constructor body,
as when it begins to execute it's too late. What
you have in your code below is not initialization,
it's assignment, not the same thing.
What is the proper way to initialise.

Initializer list. See below.
The code is given below.
Regards,
santosh




class NamedPtr
{
const string a;
const int i;
const int* ptr_int;
public:
NamedPtr(const string &s,int * x,int b=90)
{
cout<<"constor"<<endl;
//=b;
//s;
//r_int=x;
}

NamedPtr(const string& s, int *x, int b = 90)
: a(s), ptr_int(x), i(b) /* initializer list */
{
}

-Mike
 
J

John Dibling

Use an intiialization list:

NamedPtr(const string &s,int * x,int b=90)
: a(s), ptr_int(x), i(b)
{
cout<<"constor"<<endl;
}

Take care,
</dib>
 
L

Lionel B

santosh said:
Hello,
I have const member in the class.
How can I initialise these.
I can not initialise in constructor ,(it is giving compilation error)
What is the proper way to initialise.
The code is given below.
Regards,
santosh

class NamedPtr
{
const string a;
const int i;
const int* ptr_int;
public:
NamedPtr(const string &s,int * x,int b=90)
{
cout<<"constor"<<endl;
//=b;
//s;
//r_int=x;
}

NamedPtr(const string &s,int * x,int b=90) : a(s), i(b), ptr_int(x),
{
cout<<"constor"<<endl;
...
}
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top