bomba6
bomba6

Reputation: 579

Array of Classes and assignment operator

I'm New to C++, and I'm trying to do the following thing:

I have a simple class, called "sim". I want to create an array of 10 elements of type class "sim". So I've used sim** a = new sim*[10].

Then I ran in a loop, and create new elements like a[i]=new sim(i). But when I later try to print the values (fields) of each of the a[i]'s, I don't get what I except to.

Here is the code:

#include "stdafx.h"
#include <iostream>
using namespace std;

class sim{
private:
    int x;
    const int y;
public:
    sim();
    sim(int z);
    ~sim();
    void showInfo();
    sim& operator=(const sim& s);
};

sim::sim():y(10),x(0)
    {}

sim::sim(int z):y(10),x(z)
    {}

sim::~sim()
    {}

void sim::showInfo()
    {
    cout<<"x="<<x<<", y="<<y<<endl;
    }

sim& sim::operator=(const sim& s)
    {
    x=s.x;
    return *this;
    }

int _tmain(int argc, _TCHAR* argv[])
{
    sim** a = new sim*[10];
    for(int i=0;i<10;i++)
    {
        a[i]= new sim(i);
    }

    for(int i=0; i<10; i++)
        (*a)[i].showInfo();
    getchar();
    return 0;
}

And here is the wrong output:

x=0, y=10
x=-33686019, y=-830047754
x=-33686019, y=-572662307
x=1869774733, y=201385040
x=725928, y=726248
x=1423328880, y=11
x=24, y=2
x=55, y=-33686019
x=4814584, y=-1
x=0, y=0

Y should be 10 always, and x should be 0-9. What am I doing wrong? Thanks!

Upvotes: 1

Views: 201

Answers (2)

antonijn
antonijn

Reputation: 5760

(*a)[i].showInfo();

This is not right. This will produce the same output as:

(*((*a) + i)).showInfo();

Which is quite clearly not what you want.

You are trying to access the showInfo method of the object stored at the address that the i-th value of a points to.

So you should write this:

(*(a[i])).showInfo();

And then you could add some syntactical sugar to that, so that you don't have that awful dereference operator:

a[i]->showInfo();

Upvotes: 2

user1898811
user1898811

Reputation:

The problem is the order of operations in your statement

(*a)[i].showInfo();

This is dereferencing a, giving you a point to a sim instance, then you are indexing into this. Instead, you should index into a, then dereference the result:

(*(a[i])).showInfo();

The parenthesis above are for clarity's sake. Given C++ operator precedence, you could safely write that line as:

(*a[i]).showInfo();

The reason for your bizarre output is that you are indexing off of the first sim instance you allocated with new, which is at some arbitrary location in heap memory. You are simply treating the subsequent chunks of memory as though they were sim instances, which leads to undefined member values.

Upvotes: 2

Related Questions