473,763 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem about array of object

Hi,

I have an object "elem", there are only simple functions inside, like
setName, getName, and three constructors

Now I have another class "Base", need an array of elem to initialize

class Base
{
public:
Base( elem **elements, int count );

protected:
elem **_elements;

}

I don't want to use outside pointer, which means I don't want _elements =
elements, actually, it works well except the problem of security

Therefore, in the Base constructor, I want to allocate a new space for the
array

Base::Base(elem **elements, int count)
{
// _elements = elements; // do not use this

_elements = new elem[count];

for (int i=0; i< count; i++)
{
assert(elements[i]!=NULL);
_elements[i] = new elem(elements[i]->getName());
cout << elements[i]->getName() << endl;
}
}

But, a strange problem is here, there are some elements lose "Name" !

What I mean is when I print elements[i]->getName(), which returns a char,
some of them are missed, become empty

even I move this line before "assert"

If I just set _elements = elements, and then print, nothing will be missed

Now I am really clueless, anyone has an idea?

Thank you very much!

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
Jul 23 '05 #1
8 1985

Sowen wrote:
Hi,

I have an object "elem", there are only simple functions inside, like setName, getName, and three constructors

Now I have another class "Base", need an array of elem to initialize

class Base
{
public:
Base( elem **elements, int count );

protected:
elem **_elements;

}
How about taking const reference to 'std::vector'?

Base(const std::vector<ele m>& elements);

If elem has value-semantics, (in particular a copy constructor), this
works quite well for you: it's easy for clients to create such a
vector, the vector length ('count') comes for free, and memory
management comes for free.
I don't want to use outside pointer, which means I don't want _elements = elements, actually, it works well except the problem of security
If you have a data member 'std::vector<el em> d_elements' in your 'Base'
class, all you have to do is assign 'd_elements = elements' in your
constructor.
Therefore, in the Base constructor, I want to allocate a new space for the array


You probably don't "want" to, but your implementation is forcing you
to. Use 'std::vector'.

BTW, the name 'Base' hints at polymorphism, but your class is not a
polymorphic base class. You should consider changing the name.

/david

Jul 23 '05 #2
Hi,
thanks for your reply

my class is not named as "Base", I just use it for question

and I can't use "vector" in here, otherwise, I won't use array :(

I think even I don't use "vector", this should be done. I just don't
understand why I allocate a new space for a local variable, but the
parameter loses data

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
<da********@war pmail.net> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...

Sowen wrote:
Hi,

I have an object "elem", there are only simple functions inside, like

setName, getName, and three constructors

Now I have another class "Base", need an array of elem to initialize

class Base
{
public:
Base( elem **elements, int count );

protected:
elem **_elements;

}


How about taking const reference to 'std::vector'?

Base(const std::vector<ele m>& elements);

If elem has value-semantics, (in particular a copy constructor), this
works quite well for you: it's easy for clients to create such a
vector, the vector length ('count') comes for free, and memory
management comes for free.
I don't want to use outside pointer, which means I don't want

_elements =
elements, actually, it works well except the problem of security


If you have a data member 'std::vector<el em> d_elements' in your 'Base'
class, all you have to do is assign 'd_elements = elements' in your
constructor.
Therefore, in the Base constructor, I want to allocate a new space

for the
array


You probably don't "want" to, but your implementation is forcing you
to. Use 'std::vector'.

BTW, the name 'Base' hints at polymorphism, but your class is not a
polymorphic base class. You should consider changing the name.

/david

Jul 23 '05 #3
Sowen wrote:
Hi,

I have an object "elem", there are only simple functions inside, like
setName, getName, and three constructors

Now I have another class "Base", need an array of elem to initialize

class Base
{
public:
Base( elem **elements, int count );

protected:
elem **_elements;

}
Missing semicolon (;).

I don't want to use outside pointer, which means I don't want _elements =
elements, actually, it works well except the problem of security

Therefore, in the Base constructor, I want to allocate a new space for the
array

Base::Base(elem **elements, int count)
{
// _elements = elements; // do not use this

_elements = new elem[count];
This should be a compile-time error. You're assigning a pointer-to-elem
to a variable of type pointer-to-pointer-to-elem.

for (int i=0; i< count; i++)
{
assert(elements[i]!=NULL);
_elements[i] = new elem(elements[i]->getName());
cout << elements[i]->getName() << endl;
}
}

But, a strange problem is here, there are some elements lose "Name" !

What I mean is when I print elements[i]->getName(), which returns a char,
some of them are missed, become empty

even I move this line before "assert"

If I just set _elements = elements, and then print, nothing will be missed

Now I am really clueless, anyone has an idea?


Please post real code that demonstrates the problem.
Jul 23 '05 #4
hi, thx for your reply

pls forget the semicolon mistake

they are real code

elem ** _elements is an object array

I don't understand why you say > This should be a compile-time error.
You're assigning a pointer-to-elem
to a variable of type pointer-to-pointer-to-elem.
my program can compile
I can post again

_elements = elements;

Base::Base(elem **elements, int count)
{
// _elements = elements;

*_elements = new elem[count];

cout << "start copying..." << endl;

for (int i=0; i< count; i++)
{
cout << elements[i]->getName() << endl;
assert(elements[i]!=NULL);
_elements[i] = new elem(elements[i]->getName());
}

}

I try different constructors, copy, defaultt, and my own constructor, they
will have the same problem
even I don't assign _elements[i] = new elem(elements[i]->getName());

before this line, if I call "*_elements = new elem[count]; ", the parameter
"elements" has been changed, some of them lost data, that means when I print
elements[i]->getName() , they are empty

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
"Jeff Schwab" <je************ @rcn.com> wrote in message
news:1b******** ************@rc n.net... Sowen wrote:
Hi,

I have an object "elem", there are only simple functions inside, like
setName, getName, and three constructors

Now I have another class "Base", need an array of elem to initialize

class Base
{
public:
Base( elem **elements, int count );

protected:
elem **_elements;

}


Missing semicolon (;).

I don't want to use outside pointer, which means I don't want _elements =
elements, actually, it works well except the problem of security

Therefore, in the Base constructor, I want to allocate a new space for
the array

Base::Base(elem **elements, int count)
{
// _elements = elements; // do not use this

_elements = new elem[count];


This should be a compile-time error. You're assigning a pointer-to-elem
to a variable of type pointer-to-pointer-to-elem.

for (int i=0; i< count; i++)
{
assert(elements[i]!=NULL);
_elements[i] = new elem(elements[i]->getName());
cout << elements[i]->getName() << endl;
}
}

But, a strange problem is here, there are some elements lose "Name" !

What I mean is when I print elements[i]->getName(), which returns a char,
some of them are missed, become empty

even I move this line before "assert"

If I just set _elements = elements, and then print, nothing will be
missed

Now I am really clueless, anyone has an idea?


Please post real code that demonstrates the problem.

Jul 23 '05 #5
Hi,

Questions:

What is the value of "_elements[i]->getName()" right after

"_elements[i] = new elem(elements[i]->getName());" ?

is it NULL?

-if not, do you make a copy of the return string while building a new
"elem" object? Or do you simply make pointer-to-pointer assignment? In
case of the latter, check to see if the objects in the array
"elements" are not destroyed anywhere else...

-if yes, there may be something wrong with the array argument...

regards,

f.

"Sowen" <so***@anggogo. com> wrote in message news:<d1******* ***@canopus.cc. umanitoba.ca>.. .
Hi,
thanks for your reply

my class is not named as "Base", I just use it for question

and I can't use "vector" in here, otherwise, I won't use array :(

I think even I don't use "vector", this should be done. I just don't
understand why I allocate a new space for a local variable, but the
parameter loses data

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
<da********@war pmail.net> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...

Jul 23 '05 #6


"yilled_fre d" <yi********@gma il.com> wrote in message
news:43******** *************** **@posting.goog le.com...
Hi,

Questions:

What is the value of "_elements[i]->getName()" right after

"_elements[i] = new elem(elements[i]->getName());" ?

is it NULL?
some of them (elements) can keep the same, but some of them become empty
char ' '

For example, elements have five elem objects { new elem('a'); new elem('b');
new elem('c'); new elem('d'); new elem('e'); }

they can be copied to _elements, the "copy" means re-allocate a new space
for the new object

but, 'c' disappears, I can only print 'a', 'b' ,'d' , and 'e'

-if not, do you make a copy of the return string while building a new
"elem" object? Or do you simply make pointer-to-pointer assignment? In
case of the latter, check to see if the objects in the array
"elements" are not destroyed anywhere else...
no no, I don't simply make pointer-to-pointer assignment

the elem object has only one char, and 'getName()' 'setName(const char c)'
methods, and other three constructors

-if yes, there may be something wrong with the array argument...

regards,

f.

"Sowen" <so***@anggogo. com> wrote in message
news:<d1******* ***@canopus.cc. umanitoba.ca>.. .
Hi,
thanks for your reply

my class is not named as "Base", I just use it for question

and I can't use "vector" in here, otherwise, I won't use array :(

I think even I don't use "vector", this should be done. I just don't
understand why I allocate a new space for a local variable, but the
parameter loses data

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
<da********@war pmail.net> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...

Jul 23 '05 #7
"Sowen" <so***@anggogo. com> wrote in message
news:d1******** **@canopus.cc.u manitoba.ca...
Now I have another class "Base", need an array of elem to initialize

class Base
{
public:
Base( elem **elements, int count );

protected:
elem **_elements;

} Base::Base(elem **elements, int count)
{
// _elements = elements; // do not use this

_elements = new elem[count];

for (int i=0; i< count; i++)
{
assert(elements[i]!=NULL);
_elements[i] = new elem(elements[i]->getName());
cout << elements[i]->getName() << endl;
}
}


Your constructor allocates memory? Where is that memory freed?

Is there a destructor you didn't show us?

If so, what are your copy constructor and copy-assignment operators?
Jul 23 '05 #8
Sowen wrote:
hi, thx for your reply

pls forget the semicolon mistake

they are real code

elem ** _elements is an object array

I don't understand why you say > This should be a compile-time error.
You're assigning a pointer-to-elem
to a variable of type pointer-to-pointer-to-elem.

my program can compile
I can post again

_elements = elements;

Base::Base(elem **elements, int count)
{
// _elements = elements;

*_elements = new elem[count];


You've added an asterisk ('*') to what you posted earlier, but this is
still not what you want. This ought to compile, but you're likely to
get a run-time error, since you are dereferencing the uninitialized
pointer _elements.

cout << "start copying..." << endl;

for (int i=0; i< count; i++)
{
cout << elements[i]->getName() << endl;
assert(elements[i]!=NULL);
_elements[i] = new elem(elements[i]->getName());
}

}


My best guess is that your "element" class stores names as char const *,
and does only a shallow copy of the char const* being passed to its
constructor. I think the original, copied elements are going out of
scope, and their destructors are deleting their member char const*.
Some of the names are hanging around in memory for your new elements to
print, while others are getting overwritten. What you see as "space" in
each deleted name is actually a sequnce of unprintable characters that
happen to be followed by a null byte.

Can you use std::string instead of const char* for element names? Then
your implementation could look something like this:

#include <string>

struct Element
{
Element( char const* name ): m_name( name ) { }
char const* getName( ) { return m_name.c_str( ); }
private:
std::string m_name;
};

class Base
{
public:
Base( Element **elements, int count );
virtual ~Base( );

private:
Element **m_elements;
int m_count;
};

#include <cassert>
#include <iostream>
#include <iomanip>

Base::Base( Element **orig, int count ):
m_elements( new Element* [ count ] ),
m_count( count )
{
// m_Elements = Elements; // do not use this

Element** copy = m_elements;
Element** end = orig + count;

for( ; orig < end; ++orig, ++copy )
{
assert( *orig );

*copy = new Element( (*orig)->getName( ) );

std::cout << (*copy)->getName( ) << std::endl;
}
}

Base::~Base( )
{
Element** elem = m_elements;
Element** end = m_elements + m_count;

for( ; elem < end; ++elem )
{
delete *elem;
}

delete [ ] m_elements;
}

int main( )
{
Element hello( "Hello" );
Element world( "World" );
Element* elems[ ] = { &hello, &world };

Base( elems, 2 );
}
Jul 23 '05 #9

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

Similar topics

2
2970
by: Marc Schellens | last post by:
Following the NumPy documentation, I took over some C code, but run into an error. Does anybody have a suggestion? Thanks, marc gdlpython.cpp:225: `PyArray_Type' undeclared (first use this function) #include <python2.3/Python.h>
1
3895
by: tangus via DotNetMonster.com | last post by:
Hello all, I'm really struggling with getting some Active Directory code to work in ASP.NET. Can you please provide assistance? I am executing the following code: Dim enTry As DirectoryEntry = New DirectoryEntry("LDAP://domain") Dim mySearcher As New DirectorySearcher(enTry) Dim resEnt As SearchResult mySearcher.Filter = ("(objectClass=*)") mySearcher.SearchScope = SearchScope.Subtree
6
1557
by: Tom | last post by:
I have a problem, to which I have been unable to find a solution for days now, after checking numerous references (both in books and online). Perhaps someone here can help. Here's my problem: I'm trying to define a series of radio objects as a large array for a survey, like this: 1) Does this make sense? <input type="radio" name="question" value="Y"> Yes <input type="radio" name="question" value="N"> No
2
2759
by: yqlu | last post by:
I hava developed a client in C# that is connected to a 3-party XML Web Services developed in Java based on the AXIS 1.1. Most methods call are successful except for one method named "findObjects" and return a complex type "FieldSearchResult". The error message as following : "Cannot assign object of type System.String to an object of type System.String. There is an error in XML document (23, 97)." By the way,I hava written a client in Java...
2
4453
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c */ #include <time.h>
9
4098
by: mupe | last post by:
Hi, i have a problem with a Type Library, which is written in C++. I am developing an application in C#.NET and have to use functions from this COM-Type Library. When I use these functions in the "old" VB it works but not in .NET. I think it is a problem with marshalling but I could not find a solution yet. First I included the Type Library in VS.NET 2003. Other functions of the TL work so the reference to the Lib must be correct.
15
1481
by: tatsudoshi | last post by:
Hello, I have this class http://pastebin.com/807571, where I set some variables on __construct. Originaly I set the $total_? variables when the function showLayout() was called. I know pastebin is having problems, so if you can't get the code, I will upload it in plain text on my own server. This function is called from a page object, which is called from a controller and so on. Doing it this way meant that all variables set during the...
1
2070
by: DJG79 | last post by:
Hi all, I am using an open source menu that i found and it works great, except for one thing that when the web page is not scrolled to the very top the drop down links will not stay visible. Has anyone else had this sort of problem with javascript? and any ideas how to fix it would be greatly appreciated.. I have included a copy of the code below, thanks. /**
3
6350
by: raylopez99 | last post by:
Below is my problem. I've narrowed it down to one thing: my unfamiliarity on how class instances are instantiated in an array. This is because the "un-array" / "non-array" version of the program works fine (see below). So what is the problem? I get a null reference on the line below at *!&!* "Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.? RL
0
9383
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10140
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9992
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9935
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9819
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3916
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3519
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2790
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.