C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

C++ Syntax Confusion

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
Guest






PostPosted: Sun May 20, 2007 9:11 am    Post subject: C++ Syntax Confusion Reply with quote



Given the template class below, please help me understand the
following code behavior?

Array<int32> ia(10); // Array that can contain 10 int32
ia[1] = 1; // Array element 1 set to 1

Here comes the confusion part.

Array<int32> *iarrayPtr = new Array<int32>(10);

1. Does the above mean a point to an array that can contain 10
int32 ?

(*iarrayPtr)[1] = 99;

2. Assign value 99 to array element 1.

iarrayPtr[2] = 100;

3. Stepping through with the debugger, I can see Array(int32 aSize)
called with aSize set to 100. What happened here? How should I read
the above code statement?

Thanks!!!

=== ===
template<class T>
class Array :{
public:
Array(int32 aSize){dataLen = aSize;data = new T[dataLen];}
virtual ~Array(){delete [] data;}

int32 length() const{return(dataLen);}

const T& operator[](int32 i) const {return(data[i]);}

T& operator[](int32 i){return(data[i]);}

T *getData() const {return(data);}

private:
Array();
private:
T *data;
int32 dataLen;
};
Back to top
Guest






PostPosted: Sun May 20, 2007 9:11 am    Post subject: Re: C++ Syntax Confusion Reply with quote



Quote:
Array<int32> *iarrayPtr = new Array<int32>(10);

1. Does the above mean a point to an array that can contain 10
int32 ?

Ya

Quote:
2. Assign value 99 to array element 1.

iarrayPtr[2] = 100;

Here you're viewing your pointer as an array of Array<int32>
(pointers can be viewed as arrays, and an array can be viewed as r-
value pointer to its first element in C/C++). Thus you access its
third element (third Array<int32>, which you obviously didnt allocate
memory for). Now, when you toss 100 in there, an implicit convertion
takes place:

consturctor Array(int32 aSize) - gives compiler rights to implicitly
convert int32 to Array using this constructor. If you want to avoid
such errors, put explicit in front of constructor declaration:

explicit Array(int32 aSize);

Then you would need to type:

iarrayPtr[2] = Array<int32>(100);

for this to compile successfully.
Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.