-2

So i would like to have a constant pointer as field in my class becouse it must ALWAYS point to first cell. Problem is I can't do it since I am allocating memory in constructor. I was thinking about inicialization list but memory allocated is dependent on size of arguments; in C# I'd use ,,readonly''. No idea how to do it in C++

class Package{
    private: char *const pack ; // <-- here

    public: Package(PackInfo pckInfo, Data file) ;
    public: ~Package();
};

Package::Package(PackInfo pckInfo, Data data){

    this->headerSize = sizeof(pckInfo);
    this->sizeOfData = data.GetDataSize();

    //alocate memory
    this->pack = new char[this->sizeOfData + this->headerSize](); //<- can not be done
    //pointer on the begining of allocated array
    PackInfo *temp = (PackInfo*) this->pack;
    //putting header information in the begining of the array  // moving pointer at cell just after header information
    *temp = pckInfo; temp++; 
    char *packPointer = (char*)temp; 
    //getting data from file direclty into the array
    data.GetCurrentBytes(packPointer);
}
Phate P
  • 1,572
  • 1
  • 22
  • 31
  • 2
    why cannot be done? : pack(new char[sizeof(pckInfo)+data.GetDataSize()]) – Jack Dec 05 '15 at 12:41
  • Actually if pack is declared after headerSize and sizeOfData in class definition you can set them both and then allocate the array with no problems, eg : headerSize(sizeof(pckInfo)), sizeOfData(..), pack(new char[headerSize+sizeOfData]) – Jack Dec 05 '15 at 12:42
  • omg, I tried it, but seems like I did some mistake and I thought it can not be done this way. Thank You!!!! – Phate P Dec 05 '15 at 12:45
  • In general you cannot binary dump objects to files and back and expect it to work. – Neil Kirk Dec 05 '15 at 13:23

2 Answers2

2

I was thinking about inicialization list but memory allocated is dependent on size of arguments;

That doesn't prevent you:

Package::Package(PackInfo pckInfo, Data data):
    headerSize(sizeof(pckInfo)),
    sizeOfData(data.GetDataSize()),
    pack(new char[this->sizeOfData + this->headerSize]())
{
    // … 
}

Just make sure both headerSize and sizeOfData are declared before pack in the class definition: The member initialization order is the same as their declaration order in the class body.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

To initialise something constant in the constructor, use the member initialiser list e.g.

Package::Package(PackInfo pckInfo, Data data)
    : pack = new char[required_size_here]
{
    //... as you were
}

You need to make sure you have the sizes set before you use them. Left as an exercise for the reader.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
  • Did you read all question before anwsering? I already know that, but as u can see the memory i want to allocate is not known before consturctor is called. It is the size of arguments passed to constructor. – Phate P Dec 05 '15 at 12:35
  • zenith has spelled it out for you – doctorlove Dec 05 '15 at 12:55