Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a constant data member but not initialize it until later?

Lets say in my main method, I declare a const int array pointer pointing to an array created on the heap. I then want to initialize it's values (using the memory address) in a constructor TryInitialize() and then print them out. This is not working and I'm wondering what I'm doing wrong? Thanks!

#include "stdafx.h"
#include "part_one.h"
#include <string>
#include <iostream>

using namespace std;

string createTable(unsigned int* acc, double* bal, int n) {
    string s;
    char buf[50];

    for (int i = 0; i < n; i++) {
            sprintf_s(buf,"%7u\t%10.2f\n",acc[i], bal[i]);
            s += string(buf);
    }

    return s;
}



int _tmain(int argc, _TCHAR* argv[])
{

    const int *tempInt = new const int[4];
    TryInitialize(tempInt);
    std::cout << tempInt[1] << endl;

    system("pause");

    return 0;
}

And here is my code for my constructor:

#include "part_one.h"


TryInitialize::TryInitialize(void) {

}

TryInitialize::TryInitialize(int constInt[]) {
    constInt[0] = 8;
    constInt[1] = 0;
    constInt[2] = 0;
    constInt[3] = 8;
}
like image 242
Taylor C. White Avatar asked Oct 06 '22 04:10

Taylor C. White


2 Answers

You should not change a const value.

For what you trying to accomplish I'd recommend declaring a non-const pointer and a const pointer and assigning the non-const one to the const one after the initialization:

int _tmain(int argc, _TCHAR* argv[])
{
    const int *tempTempInt = new int[4];
    TryInitialize(tempInt);
    const int* const tempInt = tempTempInt;
    std::cout << tempInt[1] << endl; //this is now constant.

    system("pause");

    return 0;
}

Also pay attention where you put the const in the pointer declaration:

const int* const tempInt = tempTempInt;

In the declaration above the second const means that you cannot change the pointer; the first const means that you cannot change the pointed value(s).

like image 183
Csq Avatar answered Oct 07 '22 18:10

Csq


You declare the pointer as const int*. The const modifier means that you cannot change the array values.

Either remove the const, or create an initializer method for it that can allocate the array and return it (unlike a constructor).

const int* init_my_array()
{
  int * ret = new int[4];
  ret [0] = 8;
  ret [1] = 0;
  ret [2] = 0;
  ret [3] = 8;
  return ret;
}
...
const int *tempInt = init_my_array();
like image 28
StoryTeller - Unslander Monica Avatar answered Oct 07 '22 17:10

StoryTeller - Unslander Monica