0

I want to create class Test with const int variable with name "a". After that I need create constructor where variable "a" get value =10. I Create class test and in test.h I create const int a; in class Test.h and in test.cpp I have something like that:

#include "stdafx.h"
#include "Test.h"


Test::Test(void)
{
    a = 10;
    b = 20;
    size = 20;
    tekst[size];
    }

Test::~Test(void)
{
}

and this is test.h:

#pragma once
class Test
{

    const int a;  



public:
    Test(void);
    ~Test(void);
    int b;
    char *tekst;
    int size;
    static double d;
    int y;
};

but I get error:

Error   1   error C2758: 'Test::a' : must be initialized in constructor base/member initializer list    c:\users\bożydar\documents\visual studio 2012\projects\consoleapplication1\consoleapplication1\test.cpp 6
Error   2   error C2166: l-value specifies const object c:\users\bożydar\documents\visual studio 2012\projects\consoleapplication1\consoleapplication1\test.cpp 7
1
  • 2
    I'm sure searching constructor base/member initializer list on Google will pull up some good results. Commented Nov 16, 2012 at 14:34

4 Answers 4

7

The error says it all, a must be initialized in constructor base/member initializer list

Test::Test(void) : a(10) // Initializer list
{
...
}
Sign up to request clarification or add additional context in comments.

Comments

3

The error tells you what to do

Test::Test(void) : a(10) // an initializer list
{
    b = 20;
    size = 20;
    tekst[size];
}

BTW i think you'll find that the code

tekst[size];

does not do what you expect it to. Probably you mean

tekst = new char[size];

1 Comment

The initializer list should be used for everything, not just for those cases where you absolutely must... And the local declaration of tekst is completely off.
1

You have to do it in an initialization list:

Test::Test(void) : a(10) {
  ...
}

Comments

0

a is const, so you cannot assign to it. You must, however, initialize it.

Do:

Test::Test(void)
:a(10)
{
    ...
}

BTW, the tekst[size] doesn't do what you think, probably. It does nothing!

1 Comment

It might do nothing. It might do something. Technically, its behavior is undefined.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.