Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer to class object

Status
Not open for further replies.

ceodav

Programmer
Feb 21, 2003
106
IT
Hi,
i use an array af class object like the follow but i'm misunderstanding something...


if i write

Cnet *R[100];

for(int i=0; i<100; i++)
{
R = new CNeuralNet;

}

and then inside the destructor

for(int i=0; i<100; i++)
{
delete R;
}

it works fine and when i call the object

r->....

infact i don't get any error...

but if i write

Cnet *R;
R = new CNeuralNet [100];

and then inside the destructor

delete[] R;

i get errors when i call the functions inside the class i created

r->....


the error is :

error C2819: type 'Cnet' does not have an overloaded member 'operator ->'
: see declaration of 'Cnet'


Where is the problem?


thanks
D.
 
In the first version of your code, R is an array of pointers on Cnet instances.
So
Code:
R[i]
is of type Cnet* , and you have to write
Code:
R[i]->do_somthing ();
to call routines on that item.

In the second version, R is just a pointer on a Cnet instance, and you want to use that pointer as an array like the previous one. You could also write :
Code:
 Cnet R[100];//don't have to delete anything
So
Code:
R[i]
is of type Cnet , and you have to write
Code:
R[i].do_something ();
to call routines on that item.
That's why you get an error when writing
Code:
R[i]->...
.
Notice that you don't have to delete instances in the second version, but just the array.

If you want to use array of instances, I advise you to use class vector from STL.

--
Globos
 
1. to free correctly an array of objects you should do like this:
for(int i = 0; i < 100; i++)
{
delete R;
}
delete[] R;

2. if is declared R as XXX R[yy] you can not
delete[] R; and you can not initialize R to another array like
R = anotherarray; because it is a constant array.
so you can do
XXX* R;
R = new XXX[100];
for(i = 0 ; i < 100.... initialize R

and in destructor delete like is writen above in 1.
[/code]


Ion Filipski
1c.bmp
 
Code:
1. to free correctly an array of objects you should do like this:    
    for(int i = 0; i < 100; i++)
    {
        delete R[i];
    } 
    delete[] R;

2. if is declared R as XXX R[yy] you can not 
delete[] R; and you can not initialize R to another array like 
R = anotherarray; because it is a constant array.
so you can do 
XXX* R;
R = new XXX[100];
for(i = 0 ; i < 100.... initialize R[i]

and in destructor delete like is writen above in 1.


Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top