473,320 Members | 2,052 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,320 software developers and data experts.

C++ Syntax Confusion

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

Array<int32ia(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;
};

May 20 '07 #1
4 1723
Array<int32*iarrayPtr = new Array<int32>(10);

1. Does the above mean a point to an array that can contain 10
int32 ?
Ya
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.

May 20 '07 #2
On May 20, 9:46 am, coder_...@yahoo.com wrote:
Given the template class below, please help me understand the
following code behavior?

Array<int32ia(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 ?

hello,

according to my understanding ..In your first point..it means a
pointer of Array<int32 that points to Array<int32>(10). it's not
exactly pointing to array of 10 int32.
let take for exp..

int *ptr = new int(10); here it's pointing to integer that's
initialized to 10.
and
int *ptr = new int[10]; but here points to array of 10 integer;
although explicit conversion is there..in second case "iarrayPtr[2] =
100"..and one can avoid it using explicit keyword with the class
constructor..

but coming on to your third point..
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?
How can Array(int32 aSize) constructor be called with 100 as
aSize??..when you are passing 10 as value.?

now see code below..made default constructor as public. Set the aSize
as "10";
Array<int32*iarrayPtr = new Array<int32>[10];

now iarryPtr is pointer that points to Array of 10 Array<int32>(10).
typedef int int32;
using namespace std;

template<class T>
class Array {
public:
Array() {dataLen = 10;data = new T[dataLen];}
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;
};
int main()
{

Array<int32ia(10); // Array that can contain 10 int32
ia[1] = 1; // Array element 1 set to 1
Array<int32*iarrayPtr = new Array<int32>[10];
(*(iarrayPtr+9))[9] = 99;
cout <<(*(iarrayPtr+9))[9]<<endl;
iarrayPtr[9][9] = 100;
cout <<iarrayPtr[0].length()<<endl;
cout <<iarrayPtr[9][9]<<endl;

return 0;
}
pls let me know if i'm wrong somewhere..:-).

May 20 '07 #3

<dh**************@gmail.comwrote in message ...
On May 20, 9:46 am, coder_...@yahoo.com wrote:
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 ?

hello,
according to my understanding ..In your first point..it means a
pointer of Array<int32 that points to Array<int32>(10). it's not
exactly pointing to array of 10 int32.
let take for exp..

int *ptr = new int(10); here it's pointing to integer that's
initialized to 10.
and
int *ptr = new int[10]; but here points to array of 10 integer;
although explicit conversion is there..in second case "iarrayPtr[2] =
100"..and one can avoid it using explicit keyword with the class
constructor..

but coming on to your third point..
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?

How can Array(int32 aSize) constructor be called with 100 as
aSize??..when you are passing 10 as value.?

now see code below..made default constructor as public. Set the aSize
as "10";
Array<int32*iarrayPtr = new Array<int32>[10];

now iarryPtr is pointer that points to Array of 10 Array<int32>(10).

typedef int int32;
using namespace std;
template<class Tclass Array { public:
Array() {dataLen = 10;data = new T[dataLen];}
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;
};
int main(){
Array<int32ia(10); // Array that can contain 10 int32
ia[1] = 1; // Array element 1 set to 1
Array<int32*iarrayPtr = new Array<int32>[10];
(*(iarrayPtr+9))[9] = 99;
cout <<(*(iarrayPtr+9))[9]<<endl;
iarrayPtr[9][9] = 100;
cout <<iarrayPtr[0].length()<<endl;
cout <<iarrayPtr[9][9]<<endl;
return 0;
}

pls let me know if i'm wrong somewhere..:-).
Not wrong, but I'd use init lists:

template<class Tclass Array{ public:
Array() : dataLen( 10 ), data( new T[dataLen] ){}
Array( int32 aSize )
: dataLen( aSize ), data( new T[dataLen] ){}
// alt: replace the 2 Ctors above with:
// Array( int32 aSize = 10 )
// : 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: // note the order of the following.
int32 dataLen;
T *data;
};

And maybe use 'function-level try blocks':

template<class Tclass Array{ public:
Array( int32 aSize = 10 )
try : dataLen( aSize ), data( new T[dataLen] ){}
catch( std::bad_alloc const &sba ){
// handle error and/or (re-)throw something.
}
// ......
};
--
Bob R
POVrookie
May 20 '07 #4
On May 20, 6:46 am, coder_...@yahoo.com wrote:
Given the template class below, please help me understand the
following code behavior?
Array<int32ia(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 ?
It's a pointer to a single array which can containt 10 elements,
yes.
(*iarrayPtr)[1] = 99;
Correct. Dereferencing the pointer results in the array itself.
2. Assign value 99 to array element 1.
iarrayPtr[2] = 100;
This is undefined behavior. For historical reasons, [] is
defined on pointers, and is the exactly equivalent (in this
case) of *(iarrayPtr + 2). In short, you are assigning 100 to
the third Array object allocated by new. Which is wrong for
several reasons: first, you didn't allocate three objects, only
one, so what you get it undefined behavior, and second, you
haven't defined an assignment operator for Array objects, so the
compiler generated one will be used, and I'm 100% certain it
doesn't do what you want (since it does a shallow copy).
Finally, of course, you're assigning an int, and not an Array
object, so in the absence of an explicit "operator=(int)" in
your Array class, the compiler will try to convert the int to an
Array object.
3. Stepping through with the debugger, I can see Array(int32 aSize)
called with aSize set to 100. What happened here?
The compiler is doing what you told it to do, not what you
actually want:-). See my answer to 2. Also, you "told" the
compiler that it could implicitly convert an int to an Array
object.
=== ===
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;
};
Given this:
-- you definitly want to declare the constructor explicit, and
-- you either want to define a copy constructor and assignment
operator with the semantics you want, or declare them
private, so that the compiler can't use them just anywhere.
Neither of these corrections, however, will allow you to refer
the the third Array object when you've only allocated one.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 20 '07 #5

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

Similar topics

699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
23
by: C. Barnes | last post by:
I vote for def f(): (body of function) This is backwards compatible (Python <= 2.3 raise SyntaxError), and looks much nicer than @. The only problem is that you can't one-line a...
24
by: Steven Bethard | last post by:
I think one of the biggest reasons we're having such problems coming to any agreement on decorator syntax is that each proposal makes a number of syntax decisions, not just one. For decorators, I...
24
by: deko | last post by:
I'm trying to log error messages and sometimes (no telling when or where) the message contains a string with double quotes. Is there a way get the query to insert the string with the double...
177
by: C# Learner | last post by:
Why is C syntax so uneasy on the eye? In its day, was it _really_ designed by snobby programmers to scare away potential "n00bs"? If so, and after 50+ years of programming research, why are...
23
by: Marcin Grzębski | last post by:
I red MSDN article of C# 2.0 this week... and i found very strange syntax for properties e.g.: public int MyIntValue { get { // ... } protected set { // ... }
2
by: bor_kev | last post by:
Hi, First of all, i want to use the new managed class syntax and STL.NET under Microsoft Visual (C++) Studio 2005 Beta. I read in a Microsoft...
2
by: JJA | last post by:
I'm looking at some code I do not understand: var icons = new Array(); icons = new GIcon(); icons.image = "somefilename.png"; I read this as an array of icons is being built. An element of...
20
by: W Karas | last post by:
Would the fear factor for concepts be slightly reduced if, instead of: concept C<typename T> { typename T::S; int T::mem(); int nonmem(); };
4
by: BD | last post by:
Hi, all.. I'm creating a table with one column of type DATE, non nullable, with a default of the current date. The column syntax I'm using is "THIS_DATE_1 DATE NOT NULL DEFAULT CURRENT...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shćllîpôpď 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.