This semester in university I have a class called Data Structures, and the professor allowed the students to choose their favourite language. As I want to be a game programmer, and I can’t take Java anymore, I chose C++ … but now I’m stuck with lack of knowledge in this language. I have to do the following: create a SuperArray, which is like a Delphi array (you can choose the starting and ending index of it). My code is as follows:
main.cpp
#include <iostream>
#include "SuperArray.h"
using namespace std;
int main(int argc, char** argv)
{
int start, end;
cout << "Starting index" << endl;
cin >> start;
cout << "Ending index:" << endl;
cin >> end;
SuperArray array = new SuperArray(start,end);
}
superarray.h
#ifndef _SUPERARRAY_H
#define _SUPERARRAY_H
class SuperArray
{
public:
SuperArray(int start, int end);
void add(int index,int value);
int get(int index);
int getLength();
private:
int start, end, length;
int *array;
};
#endif /* _SUPERARRAY_H */
superarray.cpp
#include "SuperArray.h"
SuperArray::SuperArray(int start, int end)
{
if(start < end)
{
this->start = start;
this->end = end;
this->length = (end - start) + 1;
this->array = new int[this->length];
}
}
void SuperArray::add(int index, int value)
{
this->array[index-this->start] = value;
}
int SuperArray::get(int index)
{
return this->array[index-this->start];
}
When I try to compile this code, I have the following error:
error: conversion from `SuperArray*' to non-scalar type `SuperArray' requested
What should I do?
Unlike Java, in C++ you don’t need to use the
newkeyword to create objects. In Java, all objects are stored on the heap (free store) and can only be accessed via references.In C++, objects can be value types. You can declare them directly on the stack, e.g.
And you can call methods like:
This object will be automatically destroyed when
arraygoes out of scope. If you want to manage the lifetime of thearrayobject manually, you can optionally create it on the heap usingnew, but then you have to refer to it with a pointer:Now, you must call methods like this:
since
arrayin this case is a pointer to aSuperArrayand not aSuperArrayitself (and a pointer has nogetmethod of its own). The->operator means to use the.operator on the pointed-to object.In this case, the object pointed to by the
arraypointer will continue to exist until you calldelete array;If you fail to explicitly delete the object, it will never be deallocated (C++ has no garbage collector!) and you will have a memory leak.Note that C++ has things called “pointers” and things called “references”. A Java “reference” has some of the properties of both of these things and is not directly equivalent to either. A good introductory text on C++ should explain the difference between these.