Dynamic Memory Allocation for Objects - c++

#include <iostream>
class MyClass
{
public:
MyClass() {
itsAge = 1;
itsWeight = 5;
}
~MyClass() {}
int GetAge() const { return itsAge; }
int GetWeight() const { return itsWeight; }
void SetAge(int age) { itsAge = age; }
private:
int itsAge;
int itsWeight;
};
int main()
{
MyClass * myObject[50]; // define array of objects...define the type as the object
int i;
MyClass * objectPointer;
for (i = 0; i < 50; i++)
{
objectPointer = new MyClass;
objectPointer->SetAge(2*i + 1);
myObject[i] = objectPointer;
}
for (i = 0; i < 50; i++)
std::cout << "#" << i + 1 << ": " << myObject[i]->GetAge() << std::endl;
for (i = 0; i < 50; i++)
{
delete myObject[i];
myObject[i] = NULL;
}
I am wondering why the objectPointer must be inside the for loop, if I take it out and place it right before the for loop, I get nonsensical results. Help would be appreciated, thanks...sorry for the terrible formatting.

myObject[i] = objectPointer;
It should be inside the loop because you are storing a new reference in the array of the pointers. If it is outside the loop, then all the array of pointers point to the same reference. In such scenario, you should be careful while deallocation as all the array of pointers point to the same memory location.

Related

Exception thrown: read access violation. **this** was 0xCCCCCCCC

I'm trying to build an understanding of objects, arrays, and pointers. When I compile my code I ended up with 0xCCCCCCCC. I understand that this error is probably due to an uninitialized pointer. The problem is I don't know where or how to.
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
};
void createPerson(Person* person[]);
int main() {
Person* person[5];
createPerson(person);
for (int i = 0; i < 5; i++) {
cout << person[i]->name << endl;
}
return 0;
}
void createPerson(Person* person[]) {
string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" };
for (int i = 0; i < 5; i++) {
person[i]->name = n[1];
}
}
I'm trying to get the list of names to display.
The Problem is you have an Array of Person Person* person[] pointers and not an array of persons. I fixed the code and removed the pointers:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
};
void createPerson(Person person[]);
int main() {
Person person[5];
createPerson(person);
for (int i = 0; i < 5; i++) {
cout << person[i].name << endl;
}
return 0;
}
void createPerson(Person person[]) {
string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" };
for (int i = 0; i < 5; i++) {
person[i].name = n[i];
}
}
As you can see I removed the pointer from your array definitions. This way the Person object gets initialized on the stack. In your way the pointers get initialized, but they dont point to anything. Thats why you get your error, because the pointers are dangling. If you really want to use an array of pointer you have to initialize these pointers like this:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
};
void createPerson(Person* person[]);
int main() {
Person* person[5];
createPerson(person);
for (int i = 0; i < 5; i++) {
cout << person[i]->name << endl;
//delete person so that we dont leak mem
delete person[i];
}
return 0;
}
void createPerson(Person* person[]) {
string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" };
for (int i = 0; i < 5; i++) {
person[i] = new Person();
person[i]->name = n[i];
}
}
BTW: I would not use pointers this way. If you are new and try to understand stuff its fine to experiment. But you should almost always use smart_pointers like std::shared_ptr etc. The next thing to experiment with should be containers and proper data structures.
You are declaring an array of pointers of Person, but not initializing those pointers. By default, a pointer can point to some random location based on what garbage value is stored in its respective address (in this case 0xCCCCCCCC).
Solution is simple, just allocate a new memory using new keyword.
Also, since you are using new to allocate memory, you should call delete to de-allocate memory when you no longer require those pointers.
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
};
void createPerson(Person* person[]);
int main() {
Person* person[5];
createPerson(person);
for (int i = 0; i < 5; i++) {
if (person[i] != nullptr)
cout << person[i]->name << endl;
}
for (int i = 0; i < 5; i++) {
if (person[i] != nullptr)
delete person[i];
}
return 0;
}
void createPerson(Person* person[]) {
string n[5] = { "Dwayne Johnson", "Connor McGregor", "SpongeBob","BatMan", "Ash Ketchum" };
for (int i = 0; i < 5; i++) {
person[i] = new Person();
person[i]->name = n[i];
}
}
In C++, you can use smart pointers instead of raw pointers also. See this

C++ class objects copy constructor and operator=

I'm currently building a library In C++. I have met this problem few days ago and I'm unable to fix it. I have shorten the code so it can be seen easier.
Below is my code:
class String
{
private:
mutable char* v;
mutable int l = 0;
public:
String()
{
l++;
v = new char[1];
*v = '\0';
}
String(const char* value)
{
int length = 0;
while (value[length])
length++;
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
}
String(const String& value)
{
int length = value.len();
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
}
int len() const
{
return l - 1;
}
char* val() const
{
return v;
}
char* operator=(const char* value) const
{
delete[] v;
int length = 0;
while (value[length])
length++;
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
return v;
}
char* operator=(const String& value) const
{
delete[] v;
int length = value.len();
l = length + 1;
v = new char[l];
for (int i = 0; i < length; i++)
v[i] = value[i];
v[l - 1] = '\0';
return v;
}
char operator[](const int& index) const
{
return v[index];
}
};
class StringArray
{
private:
union ArrayDef
{
public:
mutable String stringV;
mutable int intV;
ArrayDef()
{
}
ArrayDef(const String& value)
: stringV(value)
{
}
ArrayDef(const int& value)
: intV(value)
{
}
ArrayDef(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
}
String operator=(const String& value) const
{
stringV = value;
return stringV;
}
int operator=(const int& value) const
{
intV = value;
return intV;
}
ArrayDef operator=(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
return *this;
}
};
mutable ArrayDef* arrdef;
mutable int arrLen = 0;
public:
StringArray()
{
}
void add(const ArrayDef& value) const
{
ArrayDef temp[arrLen + 1];
for (int i = 0; i < arrLen; i++)
temp[i] = arrdef[i];
temp[arrLen] = value;
arrLen++;
delete[] arrdef;
arrdef = new ArrayDef[arrLen];
for (int i = 0; i < arrLen; i++)
arrdef[i] = temp[i];
}
int len() const
{
return arrLen;
}
ArrayDef val(const int& index) const
{
return arrdef[index];
}
};
And my driver code:
#include <iostream>
int main()
{
StringArray arr;
arr.add(String("Hello"));
arr.add(String("World"));
std::cout << "Length of the array: " << arr.len() << std::endl;
int indexOfString = 1;
int indexOfCharacter = 2;
char s = arr.val(indexOfString).stringV[indexOfCharacter];
std::cout << "arr[" << indexOfString << "][" << indexOfCharacter << "]: " << s << std::endl;
}
I have created two class, that is, String and StringArray class.
For String class, I need to always add a null character after the char pointer array for safety issue.
For StringArray class, I uses union because it's actually an array for multiple types.
It can be successfully compiled but it output some random character and it is different every time I run it.
Any answers will be appreciated, and please tell me why and how it don't works. Thank you.
From,
HaiQin.
This code is just a collection of antipatters that makes it difficult to study. What is the reason of making the internal data mutable? Why do you need to play with length and l where sometimes it is the length of the string, sometimes it is the size of array? The operator operator= returns char* which is a bad practice. Using const int& index as a parameter is a strange choice. You allocate arrays multiple times but you have no destructor that frees the memory.
Here your assignment operator returns a value, not reference!
ArrayDef operator=(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
return *this;
}
Next comes even more dangerous practice:
// Recollect that this is a union
ArrayDef(const ArrayDef& value)
{
intV = value.intV;
stringV = value.stringV;
}
You are assigning both fields of the union at the same time! Did you mean struct?
Try to fix that. Start with changing union to structure.
One of the things that certainly will not work is the ArrayDef copy constructor and operator=(const ArrayDef & value). This is because you may only use the active value in the union, not both at the same time. This is usually solved by using a tagged union. Is there a reason you cannot use the Standard Template Library?
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> arr;
arr.push_back(std::string("Hello"));
arr.push_back(std::string("World"));
std::cout << "Length of the array: " << arr.size() << std::endl;
constexpr int indexOfString = 1; // second string - starting from 0!
constexpr int indexOfCharacter = 2; // third character
char s = arr.at(indexOfString).c_str()[indexOfCharacter]; // using interfaces closest to the original
std::cout << "arr[" << indexOfString << "][" << indexOfCharacter << "]: " << s << std::endl;
}

Dynamic object array not working

I have one parent and two children, I want to create a dynamic array that contains the children (not allowed to use vectors). I created the classes and everything, and I get no compilation errors or warnings, but when I try to access a member of the array and print its content, nothing happens.
I'm aware there may be some bad coding style here, but I'm only interested in knowing why the array isn't working. I think it's because I created an array of objects, instead of an array of pointers to objects, I'm not sure.
(I removed the 2nd child from the code because it's irrelevant here)
#pragma warning(disable:4996)
using namespace std;
#include <iostream>
#include <cstdlib>
#include <cctype>
#include "date.h"
#define ADDRESS_SIZE 512
#define NAME_SIZE 128
#define DATE_SIZE 128
class Treatment {
protected:
int treatment_ID;
int patient_ID;
Date treatment_date;
int treatment_costs;
public:
Treatment() {}
Treatment(int treatment_ID, int patient_ID, int treatment_costs, char treatment_date[DATE_SIZE]) {
this->treatment_ID = treatment_ID;
this->patient_ID = patient_ID;
this->treatment_costs = treatment_costs;
this->treatment_date.convert_date(treatment_date);
}
void set_treatment_ID(int treatment_ID) {
this->treatment_ID = treatment_ID;
}
void read_treatment_date(void) {
treatment_date.read_date();
}
void set_treatment_date(char _date[DATE_SIZE]) {
treatment_date.convert_date(_date);
}
void set_patient_ID(int patient_ID) {
this->patient_ID = patient_ID;
}
void set_treatment_costs(int treatment_costs) {
this->treatment_costs = treatment_costs;
}
int get_treatment_ID(void) {
return treatment_ID;
}
int get_patient_ID(void) {
return patient_ID;
}
int get_treatment_costs(void) {
return treatment_costs;
}
};
class Outside_treatment : public Treatment {
private:
int clinic_num;
//class doctor;
public:
Outside_treatment() {}
Outside_treatment(int clinic_num, int treatment_ID, int patient_ID, int treatment_costs, char treatment_date[DATE_SIZE]) :Treatment(treatment_ID, patient_ID, treatment_costs, treatment_date) {
this->clinic_num = clinic_num;
}
void set_clinic_num(int clinic_num) {
this->clinic_num = clinic_num;
}
int get_clinic_num() {
return this->clinic_num;
}
void print_outside_treatment(void) {
cout << "The clinic num is " << clinic_num << "\n";
cout << "The treatment ID is " << treatment_ID << "\n";
cout << "The patient_ID is " << patient_ID << "\n";
cout << "The treatment costs are " << treatment_costs << "\n";
treatment_date.print_date();
cout << " treatment date in compare format is " << treatment_date.get_compare();
}
};
class Dynarray {
private:
Treatment *pa;
int length;
int nextIndex;
public:
Dynarray() {
pa = new Treatment[10];
length = 10;
nextIndex = 0;
}
~Dynarray() {
delete[]pa;
}
void add(Treatment &add) {
Treatment *pnewa;
if (nextIndex == length) {
length += 10;
pnewa = new Treatment[length];
for (int i = 0; i < nextIndex; ++i) {
pnewa[i] = pa[i];
}
delete[]pa;
pa = pnewa;
}
pa[nextIndex++] = add;
}
Treatment &operator[](int index) {
return *(pa + index);
}
};
int main(void) {
Outside_treatment it;
cout << "Enter the patient ID\n";
int p_id;
cin >> p_id;
it.set_patient_ID(p_id);
cin.ignore();
cout << "set treatment date\n";
it.read_treatment_date();
cout << "enter costs\n";
int costs;
cin >> costs;
it.set_treatment_costs(costs);
cout << "enter section num\n";
int sc_num;
cin >> sc_num;
it.set_clinic_num(sc_num);
it.print_outside_treatment();
Dynarray da;
da.add(it);
Treatment *yetanotherpointer = &da[0];
int i = yetanotherpointer->get_patient_ID();
cout << i << endl;
while (1);
};
You are creating an array of Treatment object instances. As such, you cannot store any derived types at all. If you try to assign an object of a derived type to a Treatmentobject, it will get sliced.
Your hunch is correct. Since you are dealing with polymorphic types, you need to store pointers to objects, not actual objects, in the array. Then you can store Treatment* pointers to objects of any derived type, eg:
class Treatment {
...
public:
...
// make the base class destructor virtual so calling
// 'delete' on a base class pointer will invoke derived
// destructors. Otherwise, if a derived class has any
// data members with a non-trivial destructor, you will
// cause leaking. When writing polymorphic classes, it
// is common practice to always define a virtual destructor,
// just in case...
//
virtual ~Treatment() {} // <-- add this
..
};
class Dynarray {
private:
Treatment **pa;
int length;
int capacity;
// prevent copying the array, otherwise you risk
// memory errors if multiple arrays own the same
// objects being pointed at and try to free them
// multiple times. Copying pointers to owned objects
// is not safe, you need a cloning mechanism to
// make deep-copies of derived types so a copied
// array can point to its own objects...
Dynarray(const Dynarray &) {}
Dynarray& operator=(const Dynarray &) {}
public:
Dynarray(int initialCapacity = 10) {
pa = new Treatment*[initialCapacity];
capacity = initialCapacity;
length = 0;
}
~Dynarray() {
for (int i = 0; i < length; ++i)
delete pa[i];
delete[] pa;
}
void add(Treatment *add) {
if (length == capacity) {
Dynarray temp(capacity + 10);
for (int i = 0; i < length; ++i) {
temp.pa[i] = pa[i];
}
Treatment *ptr = temp.pa;
temp.pa = pa;
pa = ptr;
capacity = temp.capacity;
}
pa[length++] = add;
}
Treatment* operator[](int index) {
return pa[index];
}
};
int main(void) {
Outside_treatment *ot = new Outside_treatment;
cout << "Enter the patient ID\n";
int p_id;
cin >> p_id;
ot->set_patient_ID(p_id);
cin.ignore();
cout << "set treatment date\n";
ot->read_treatment_date();
cout << "enter costs\n";
int costs;
cin >> costs;
ot->set_treatment_costs(costs);
cout << "enter section num\n";
int sc_num;
cin >> sc_num;
ot->set_clinic_num(sc_num);
ot->print_outside_treatment();
Dynarray da;
da.add(ot);
Treatment *t = da[0];
int i = t->get_patient_ID();
cout << i << endl;
while (1);
};
On the other hand, if the array doesn't need to own the objects being pointed at, just store the pointers, you can remove the delete loop in the destructor, and the caller is not required to use new to create objects being stored, and making a copy of the array is safe, eg:
class Dynarray {
private:
Treatment **pa;
int length;
int capacity;
public:
Dynarray(int initialCapacity = 10) {
pa = new Treatment*[initialCapacity];
capacity = initialCapacity;
length = 0;
}
// coping is OK since the objects being pointed
// at are not owned by the array!
Dynarray(const Dynarray &src) {
pa = new Treatment*[src.capacity];
capacity = src.capacity;
length = src.length;
for (int i = 0; i < length; ++i) {
pa[i] = src.pa[i];
}
}
Dynarray& operator=(const Dynarray &rhs) {
if (&rhs != this) {
Dynarray temp(rhs);
Treatment **ptr = temp.pa;
temp.pa = pa;
pa = ptr;
capacity = rhs.capacity;
length = rhs.length;
}
return *this;
}
~Dynarray() {
delete[] pa;
}
void add(Treatment *add) {
if (length == capacity) {
Dynarray temp(capacity + 10);
for (int i = 0; i < length; ++i) {
temp.pa[i] = pa[i];
}
Treatment **ptr = temp.pa;
temp.pa = pa;
pa = ptr;
capacity = temp.capacity;
}
pa[length++] = add;
}
Treatment* operator[](int index) {
return pa[index];
}
};
int main(void) {
Outside_treatment ot;
cout << "Enter the patient ID\n";
int p_id;
cin >> p_id;
ot.set_patient_ID(p_id);
cin.ignore();
cout << "set treatment date\n";
ot.read_treatment_date();
cout << "enter costs\n";
int costs;
cin >> costs;
ot.set_treatment_costs(costs);
cout << "enter section num\n";
int sc_num;
cin >> sc_num;
ot.set_clinic_num(sc_num);
ot.print_outside_treatment();
Dynarray da;
da.add(&ot);
Treatment *t = da[0];
int i = t->get_patient_ID();
cout << i << endl;
while (1);
};

can't return pointer in class [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 8 years ago.
#include "C_IntArray.h"
C_IntArray::C_IntArray()
{
m_Array = 0;
m_Length = 0;
}
C_IntArray::~C_IntArray(void)
{
delete m_Array;
m_Length = 0;
}
void C_IntArray::ContructorWithParater(int *intArray, int size)
{
m_Array = new int[size];
m_Length = size;
for (int i = 0; i < size; i++)
m_Array[i] = intArray[i];
}
void C_IntArray::InputArray()
{
cout << "Nhap so luong phan tu: ";
cin >> m_Length;
m_Array = new int [m_Length];
for(int i = 0; i < m_Length; i++)
{
cout << "Nhap phan tu Array[" << i << "] = ";
cin >> m_Array[i];
}
}
void C_IntArray::OutputArray()
{
for(int i = 0; i < m_Length; i++)
cout << m_Array[i] << " ";
}
C_IntArray C_IntArray::Remove(int x)
{
C_IntArray temp;
temp.ContructorWithParater(m_Array, m_Length);
temp.OutputArray();
for(int i = 0; i < temp.m_Length; i++)
{
if(temp.m_Array[i] == x)
{
{
temp.m_Length--;
for(int j = i; j < temp.m_Length; j++)
temp.m_Array[j] = temp.m_Array[j + 1];
}
}
cout << "\n";
temp.OutputArray();
}
cout << "\n";
return temp;
}
File Header
#include <iostream>
using namespace std;
#ifndef _C_IntArray_h
#define _C_IntArray_h
class C_IntArray
{
private:
int *m_Array, m_Length;
public:
C_IntArray();
~C_IntArray();
// khoi tao tham so dau vao
void ContructorWithParater(int *, int);
void InputArray();
void OutputArray();
// xoa phan tu trung
C_IntArray Remove(int );
};
#endif _C_IntArray_h;
File main
#include "C_IntArray.h"
void main()
{
C_IntArray a;
a.InputArray();
int giaTriCanXoa = 5;
C_IntArray b = a.Remove(giaTriCanXoa);
b.OutputArray();
cout << "\n";
a.OutputArray();
system("pause");
}
i have tried to debug my project. the function Remove in class is work, and when i'm debug to return temp it still work, but i'm debug next it return NULL or return 1 array
function Remove in class can't return temp.
if i remove destructor or my temp is static C_IntArray, my project can run.
if I have misspelled the desire to help people fix.
thank you for the attention.
Remove returns a copy of the class, not a pointer. Therefore it is a copy.
Since you do not define a copy constructor or an assignment operator then you'll be using the default copy/assign - which will result in m_Array being deleted more than once.
You can either perform a deep copy of the internal array when copying the class or use Copy on Write and reference counting.
i.e. you will need to add the following functions:
C_IntArray(C_IntArray const& other);
C_IntArray& operator=(C_IntArray const& rhs);
They should allocate new storage for the data in the array and copy the elements from 'other' or 'rhs'. Look up how to write a copy constructor or assignment operator. There will be countless examples online.
There are also memory leaks in your class.
C_IntArray::InputArray() will leak memory since you do not delete m_Array before assigning new memory to it.
It would be better to use a free function for input duties rather than making it a class member - keep the interface of your class minimal and complete.
i.e. move it out of the class:
void InputArray(C_IntArray& dst) {
// ...
}
As others have suggested, just use std::vector.

C++: Passing a (pointer to an?) array of objects by reference

I'm new to C++, and I'm having significant trouble with creating an array of objects using a pass by pointer and reference. This is not the actual code; it's an example of what the code essentially does.
#include <iostream>
class MyClass
{
public:
MyClass();
static int doStuff(MyClass *&classArray);
void print_number();
private:
int number;
};
MyClass::MyClass()
{
}
int MyClass::doStuff(MyClass *&classArray)
{
int i = 0;
for (i = 0; i < 10; i++) {
*classArray[i].number = i;
}
return i;
}
void MyClass::print_number()
{
std::cout << number << "\n";
}
int main(void)
{
MyClass *test = nullptr;
int p = MyClass::doStuff(test);
std::cout << p << '\n';
for (int i = 0; i < 10; i++) {
test[i].print_number();
}
return 0;
}
When compiled, this gives a segmentation fault.
This is how you do it (don't forget do delete classArray with delete[] at the end of your program or destructor:
new operator has to have default constructor, if you want to use non-default it is easier to create copy constructor, then a temporary object and copy.
#include <iostream>
class MyClass
{
public:
MyClass();
MyClass(int x, int y);
MyClass(MyClass &OldClass);
static int doStuff(MyClass *&classArray, int Size, int x, int y);
void print_number();
private:
int number, x, y;
};
MyClass::MyClass()
{
number = 0;
x = 0;
y = 0;
}
MyClass::MyClass(int x, int y)
{
number = 0;
this->x = x;
this->y = y;
}
MyClass::MyClass(MyClass &OldClass)
{
this->number = OldClass.number;
this->x = OldClass.x;
this->y = OldClass.y;
}
int MyClass::doStuff(MyClass *&classArray, int Size, int x, int y)
{
if (Size > 0)
{
classArray = new MyClass[Size];
for (int i = 0; i < Size; i++)
{
classArray[i] = MyClass(x, y);
classArray[i].number = i;
}
return Size;
}
else
return 0;
}
void MyClass::print_number()
{
std::cout << number << " " << x << " " << y << "\n";
}
int main(void)
{
MyClass *test = nullptr;
int p = MyClass::doStuff(test, 10, 5, 6);
std::cout << p << '\n';
for (int i = 0; i < p; i++) {
test[i].print_number();
}
delete[] test;
std::cin.get();
return 0;
}
It is not working because you need to allocate the array, as the function is trying to access elements of an array which has yet not been initialized to hold that amount of elements. You can do this by
MyClass *test = new MyClass[array_size];
Or
MyClass test[array_size];
Or by using a resizable container such as std::vector, and changing the function parameters accordingly
*classArray[i].number = i;
You called doStuff with a null pointer, so classArray is null and is not an array. Dereferencing a null pointer results in undefined behavior and on most implementations you'll usually get a crash.
You're also dereferencing something that's not a pointer so this code will not even compile. The error I get is:
main.cpp:23:9: error: indirection requires pointer operand ('int' invalid)
*classArray[i].number = i;
^~~~~~~~~~~~~~~~~~~~~
Presumably this is just because, as you say, the code you're showing is not your real code and classArray[i].number corresponds to a pointer in your real code. But I thought I'd point this out anyway, just in case.
Given the context of your code, here's a working example of your code:
#include <iostream>
class MyClass
{
public:
MyClass() {}
static int doStuff(MyClass*& classArray, size_t sz)
{
int i = 0;
for (; i < sz; i++) {
classArray[i].number = i;
}
// not sure what you want here, but this will return sz+1 if sz>0
return i;
}
void print_number()
{
std::cout << this->number << std::endl;
}
private:
int number;
};
int main(void)
{
MyClass* test = new MyClass[10];
int p = MyClass::doStuff(test, 10);
std::cout << p << '\n';
for (int i = 0; i < 10; i++) {
test[i].print_number();
}
delete[] test;
return 0;
}
Though as others have pointed out, you are using C++, while it's a great exercise in understand how to pass pointers and arrays around, you might find the STL and C++stdlib contain a lot of these types of idioms in an 'easier to understand context'.
Here's your code with some C++ STL:
#include <iostream>
#include <vector>
class MyClass
{
public:
MyClass() {}
MyClass(int i) : number(i) {}
static int doStuff(std::vector<MyClass>& classArray, size_t sz)
{
int i = 0;
for (; i < sz; i++) {
classArray.push_back(MyClass(i));
}
// not sure what you want here, but this will return sz+1 if sz>0
return i;
}
void print_number()
{
std::cout << this->number << std::endl;
}
private:
int number;
};
int main(void)
{
std::vector<MyClass> test;
int p = MyClass::doStuff(test, 10);
std::cout << test.size() << '\n';
// can use iterators here if you want
std::vector<MyClass>::iterator itr = test.begin();
for (; itr != test.end(); itr++) {
itr->print_number();
}
return 0;
}
Hope that can help.