Why default constructor isn't enough?

B

Busin

class AA
{
public:
const int n;
};

int main()
{
AA a;
....
}

This code gives error: "C2512: 'AA' : no appropriate default constructor
available."

Then adding a constructor fixes the error.

class AA
{
public:
const int n;
AA(int m) : n(m) {}
};

int main()
{
AA a(1);
...
}

Can someone elaborate why with a const member variable, the default
constructor isn't enough? Thanks!
 
T

Thomas J. Gritzan

Busin said:
class AA
{
public:
const int n;
};

Your const variable has to be initialized at construction time, because it
could not be changed later.

Thomas
 
A

Ali Cehreli

class AA
{
public:
const int n;
};

int main()
{
AA a;
...
}

This code gives error: "C2512: 'AA' : no appropriate default constructor
available."

Then adding a constructor fixes the error.
[...]


Can someone elaborate why with a const member variable, the default
constructor isn't enough? Thanks!

What I understand from this is that a const member can only be
initialized in the initialization list, which requires a constructor.

Ali
 
J

JKop

Busin posted:
Can someone elaborate why with a const member variable, the default
constructor isn't enough? Thanks!


Looks like you must initialize a const variable.


-JKop
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top