473,395 Members | 1,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

A question on initialize a object with a pointer

Hi,

Suppose I have the following class declaration with a pointer as the
argument. And suppose I "new" an array "lengths" as the argument
"edge_lengths". Now, the polygon object is valid. Unfortunately, it
becomes invalid after I delete "lengths" array be mistake.

My question is that using object, the object's(an polygon object in
this case) internal states are encapsulated. They should not be affect
by anything operations unless the member operator. But the above
example shows that the object's internal states can be affected if
pointers are used. I'm wondering if there are any solutions to fix it.

class polygon{
public:
polygon(int edge_lengths[], int edge_count) :
_edge_lengths(edge_lengths),_edge_count(edge_count ) {}
}
private:
int *_edge_lengths;
int _edge_count;
};
Best wishes,
Peng

Aug 24 '05 #1
6 1428
You are performing a shallow copy in the class'es member initializer
list. This means that the only thing that gets copied over is the
array's address which as you mentioned can be deleted outside of the
class'es encapsulation. What you will need to do is implement the
contructor to perform a deep copy meaning you make a new local array
and copy the contents over.

For example...

class polygon
{
public:
polygon( int edge_lengths[], int edge_count ) :
_edge_count(edge_count)
{
_edge_lengths = new int[edge_count];
for( int index = 0; index < edge_count; index++ )
{
_edge_lengths[index] = edge_lengths[index];
}
}

~polygon() { if( _edge_lengths) delete [] _edge_lengths; }

private:
int *_edge_lengths;
int _edge_count;
};

Does this make sense? You want to copy all of the values from the one
array into the new array. Now here is the catch, you are going to need
to make sure you add a destructor to your polygon class to deallocate
the new array, and you need to make sure that whatever is in the array
supports the "=" operator so the deep-copy assignes correctly.

I hope that helps.

Aug 24 '05 #2
Ian
Pe*******@gmail.com wrote:
Hi,

Suppose I have the following class declaration with a pointer as the
argument. And suppose I "new" an array "lengths" as the argument
"edge_lengths". Now, the polygon object is valid. Unfortunately, it
becomes invalid after I delete "lengths" array be mistake.

My question is that using object, the object's(an polygon object in
this case) internal states are encapsulated. They should not be affect
by anything operations unless the member operator. But the above
example shows that the object's internal states can be affected if
pointers are used. I'm wondering if there are any solutions to fix it.

What's the point in trying to encapsulate an external object (your
lengths array)? If you want to encapsulate it and make your object
safe, copy it.

Or hold it in a smart pointer object and pass that.

Ian
Aug 24 '05 #3
Pe*******@gmail.com wrote:
Hi,

Suppose I have the following class declaration with a pointer as the
argument. And suppose I "new" an array "lengths" as the argument
"edge_lengths". Now, the polygon object is valid. Unfortunately, it
becomes invalid after I delete "lengths" array be mistake.

My question is that using object, the object's(an polygon object in
this case) internal states are encapsulated. They should not be affect
by anything operations unless the member operator. But the above
example shows that the object's internal states can be affected if
pointers are used. I'm wondering if there are any solutions to fix it.

class polygon{
public:
polygon(int edge_lengths[], int edge_count) :
_edge_lengths(edge_lengths),_edge_count(edge_count ) {}
}
private:
int *_edge_lengths;
int _edge_count;
};
Best wishes,
Peng


what about
class polygon {
public:

template < typename IntIterator >
polygon ( IntIterator from, IntIterator to )
: length_vector( from, to )
{}

private:

std::vector< int > length_vector;

};

now use length_vector[...] to access a length, and use length_vector.size()
to get the number of edges.
Best

Kai-Uwe Bux

Aug 24 '05 #4

Jordan wrote:
You are performing a shallow copy in the class'es member initializer
list. This means that the only thing that gets copied over is the
array's address which as you mentioned can be deleted outside of the
class'es encapsulation. What you will need to do is implement the
contructor to perform a deep copy meaning you make a new local array
and copy the contents over.

For example...

class polygon
{
public:
polygon( int edge_lengths[], int edge_count ) :
_edge_count(edge_count)
{
_edge_lengths = new int[edge_count];
for( int index = 0; index < edge_count; index++ )
{
_edge_lengths[index] = edge_lengths[index];
}
}

~polygon() { if( _edge_lengths) delete [] _edge_lengths; }

private:
int *_edge_lengths;
int _edge_count;
};

Does this make sense? You want to copy all of the values from the one
array into the new array. Now here is the catch, you are going to need
to make sure you add a destructor to your polygon class to deallocate
the new array, and you need to make sure that whatever is in the array
supports the "=" operator so the deep-copy assignes correctly.

I hope that helps.


I could you use deep copy. But the problem with it is that it might be
very expensive in terms of memory usage and run time. For performance
sake, sometimes it is better to use pointer, right? My question is how
to use pointer without exposing too much internal information of
objects. Thanks!

Aug 25 '05 #5
Typically, yes. Depending on what you are storing within your polygon
class (i.e. the number of polygons) it may be too expensive to perform
a deep-copy. In this case, a pointer is the way to go. However, you
might want to consider changing your design slightly.

Why are you keeping an instance within the object and one outside of
the object? If you want to be truly OOP, provide a method within the
polygon object to load your polygons and manage them internally. This
way you won't unneccessarily expose your pointers.

If you do not want to do that, do not keep a reference to the pointer
within the class. Just use the class'es members to operate on the
polygons but not hold them. Do you know what I mean?

The better option would probably be to have a polygon manager class
that handles the loading and processing of the polygons internally.

Aug 25 '05 #6

Jordan wrote:
Typically, yes. Depending on what you are storing within your polygon
class (i.e. the number of polygons) it may be too expensive to perform
a deep-copy. In this case, a pointer is the way to go. However, you
might want to consider changing your design slightly.

Why are you keeping an instance within the object and one outside of
the object? If you want to be truly OOP, provide a method within the
polygon object to load your polygons and manage them internally. This
way you won't unneccessarily expose your pointers.

If you do not want to do that, do not keep a reference to the pointer
within the class. Just use the class'es members to operate on the
polygons but not hold them. Do you know what I mean?

The better option would probably be to have a polygon manager class
that handles the loading and processing of the polygons internally.


Currently, I'm reading GoF's Design Pattern book. I'm wondering if
there is any design pattern as you mentioned.

Aug 25 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

74
by: Peter | last post by:
Hi, So many times, I have seen compile warning: "you used a char* without initilize it", probably on the code like this: ------------ char* ptr; func(..., ptr); ----------
7
by: Andi.Martin | last post by:
Hi, how is it possible, to only initialize parts of a structure. Example: typedef struct{ int a, b; ... (huge lot of members); double x,y;
15
by: Geoff Cox | last post by:
Hello, Can I separately declare and initialize a string array? How and where would I do it in the code below? It was created using Visual C++ 2005 Express Beta 2 ... In C# I would have ...
22
by: 海风 | last post by:
How to initialize a pointer in c++, Mostly, I use null, for example, char * szName = null; However, if i compile it without including afxdisp.h , .net compiler tell me that the identifier is not...
10
by: wenmang | last post by:
hi, I have following: struct array1 { int id; char *name; }; struct array2 {
3
by: windstorm | last post by:
for instance,I define a 2-D pointer: char **input = NULL; I want the "input" pointer to point to some string,and the number of the string is dynamic. when I got the first string,I was code...
4
by: Bram Kuijper | last post by:
Hi all, as a C++ newbie, I got some question on the initialization of static reference data members. Since it isn't possible to initialize static members of a class in the constructor, I...
18
by: Ehud Shapira | last post by:
Is it possible to have a declaration of a struct pointer initialized to an unnamed struct? (I'm only concerned with static/global variables, if it matters.) I'm trying to do something like: ...
3
by: Hank stalica | last post by:
So I have this class with a private data member: const Floor* const destFloor; I need to initialize f, which I'm trying to do in the constructor initializer list: Rider::Rider(const...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.