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!
sim arr[10];?stdlibrary?sim arr[10]creates an array with automatic storage of 10 sim's and default initializes them.newcreates an objects dynmically and returns a pointer to it.