J
jmsantoss
Hi,
This is a design question. I have a class named "DataBuffer" that
stores some data. After "DataBuffer" is created it can not be modified.
All the methods of "DataBuffer" are const as data can not be modified
after it was created.
Up to here everything is fine. The problem is when I want to get clever
with data storage. My program has an array of "DataBuffers" that gets
pre-allocated. If I want to use that memory instead of creating a new
"DataBuffer" each time, I get a pointer to the internal data with a
method and then I use that to fill the data directly. The problem with
this is that it breaks encapsulation as everybody has now access to the
internal data.
Alternatively, I can still use the constructor option, create a new
instance of "DataBuffer" on the stack (or previsouly allocated) with
the new data and then do a copy (operator=) to the data previously
allocated. This works and doesn't break encapsulation but is rather
inefficient as it uses two copies of the data.
I though on declaring the method of the class that stores the data a
"friend" of "DataBuffer". Unfortunately, I use inheritance and a
virtual method so "friend" does not work.
Does anybody knows of a way to do this without braking encapsulation
and without paying an efficiency penalty?
Thanks
This is a design question. I have a class named "DataBuffer" that
stores some data. After "DataBuffer" is created it can not be modified.
All the methods of "DataBuffer" are const as data can not be modified
after it was created.
Up to here everything is fine. The problem is when I want to get clever
with data storage. My program has an array of "DataBuffers" that gets
pre-allocated. If I want to use that memory instead of creating a new
"DataBuffer" each time, I get a pointer to the internal data with a
method and then I use that to fill the data directly. The problem with
this is that it breaks encapsulation as everybody has now access to the
internal data.
Alternatively, I can still use the constructor option, create a new
instance of "DataBuffer" on the stack (or previsouly allocated) with
the new data and then do a copy (operator=) to the data previously
allocated. This works and doesn't break encapsulation but is rather
inefficient as it uses two copies of the data.
I though on declaring the method of the class that stores the data a
"friend" of "DataBuffer". Unfortunately, I use inheritance and a
virtual method so "friend" does not work.
Does anybody knows of a way to do this without braking encapsulation
and without paying an efficiency penalty?
Thanks