can't return pointer in class [duplicate] - c++

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.

Related

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);
};

C++ Operator overload calling destructor

For my first try with operator overloading I created a vector class and tried to sum up two vectors. My class contains an array and a vector of int that both contain the same elements.
Addition works fine with the std::vector but I encounter two issues with the array. It seems that the destructor is called at the end of the summing operation which produces a "double free or corruption" error (core dump). Plus, the first two elements of the array are always equal to zero.
Should I also overload the delete or am I missing a thing ?
The header file:
#ifndef MYVECTOR_INCLUDE
#define MYVECTOR_INCLUDE
#include <iostream>
#include <stdexcept>
#include <cstring>
#include <vector>
class MyVector {
public:
MyVector(int n);
~MyVector();
void set(int idx, int value);
int get(int idx);
void print();
MyVector &operator=(const MyVector &v);
MyVector operator+(const MyVector &v);
private:
int *data;
std::vector<int> data_vector;
int size1;
int size2;
};
#endif
The cpp file:
#include "../include/myvector.hpp"
MyVector::MyVector(int n) {
data = new int [n];
data_vector.resize(n);
size1 = n;
size2 = 1;
}
MyVector::~MyVector() {
if (data != NULL) {
delete [] data;
}
}
void MyVector::set(int idx, int value) {
data_vector[idx] = value;
data[idx] = value;
}
int MyVector::get(int idx) {
return data_vector[idx];
}
void MyVector::print() {
std::cout << "Vector data" << std::endl;
for (int i = 0; i < size1; ++i) {
std::cout << data_vector[i] << " ";
}
std::cout << std::endl;
std::cout << "Data" << std::endl;
for (int i = 0; i < size1; ++i) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
MyVector &MyVector::operator=(const MyVector &v) {
if (this == &v)
return *this;
size1 = v.size1;
size2 = v.size2;
std::copy(v.data_vector.begin(), v.data_vector.end(), data_vector.begin());
memcpy(&data, v.data, sizeof(int)*size1);
return *this;
}
MyVector MyVector::operator+(const MyVector &v) {
if ((size1 == v.size1) && (size2 == v.size2)) {
MyVector res = MyVector(size1);
for (int i = 0; i < size1; ++i) {
res.data_vector[i] = data_vector[i] + v.data_vector[i];
res.data[i] = data[i] + v.data[i];
}
return res;
}
else
throw std::length_error("Vector dimensions must agree.");
}
Thank you.
See the rule of three/five/zero.
The rule of three states
If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.
In this case, you provided the destructor and copy assignment operator but forgot the copy constructor.
In operator+ you create a local object MyVector res which is later copied out and then destroyed. Since you haven't implemented a copy constructor, the default copy constructor will simply copy the original data pointer from res to another MyVector. When res is destroyed, the array pointed to by it's data member will be deleted, leaving the copied vector's data pointing to a deleted object.

Exception Error : Access violation reading location 0xDDDDDDDD

I am trying to create a dynamic string array in c++. When trying to display the contents of my dynamic string array to the console I receive this error:
Exception thrown at 0x0FD670B6 (msvcp140d.dll) in Assignment4.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD.
Here is my code:
DynamicStringArray.h
#pragma once
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class DynamicStringArray
{
public:
DynamicStringArray();
DynamicStringArray(DynamicStringArray &array);
~DynamicStringArray();
int getSize();
void displayContents();
void addEntry(const string &addElement);
string getEntry(int index);
int deleteEntry(const string &deleteElement);
private:
string *dynamicArray;
int size;
};
DynamicStringArray.cpp
#include "stdafx.h"
#include "DynamicStringArray.h"
#include <string>
#include <iostream>
using namespace std;
DynamicStringArray::DynamicStringArray()
{
dynamicArray = NULL;
size = 0;
}
DynamicStringArray::DynamicStringArray(DynamicStringArray &array)
{
if (dynamicArray != NULL)
{
size = 0;
delete [] dynamicArray;
dynamicArray = NULL;
}
size = array.getSize();
dynamicArray = new string[size];
for (int i = 0; i < size; i++)
dynamicArray[i] = array.dynamicArray[i];
}
DynamicStringArray::~DynamicStringArray()
{
cout << "In destructor." << endl;
delete [] dynamicArray;
dynamicArray = NULL;
}
int DynamicStringArray::getSize()
{
return size;
}
void DynamicStringArray::displayContents()
{
if (size != 0)
for (int i = 0; i < size; i++)
cout << "Item-" << i << ": " << dynamicArray[i] << endl;
else
cout << "Array is empty." << endl;
}
void DynamicStringArray::addEntry(const string &addElement)
{
string *temp = new string[size + 1];
for (int i = 0; i < size; i++)
temp[i] = dynamicArray[i];
temp[size] = addElement;
size++;
delete [] dynamicArray;
dynamicArray = temp;
delete[] temp;
}
string DynamicStringArray::getEntry(int index)
{
if ((index >= 0) && (index < size))
{
return dynamicArray[index];
}
return NULL;
}
int DynamicStringArray::deleteEntry(const string &deleteElement)
{
if(size == 0)
{
return false;
}
for (int i = 0; i < size; i++)
{
if (dynamicArray[i] == deleteElement)
{
string *temp = new string[size - 1];
for (int x = 0; x < size - 1; ++x)
{
if (x < i)
temp[x] = dynamicArray[x];
else
temp[x] = dynamicArray[x + 1];
}
delete[] dynamicArray;
dynamicArray = temp;
delete[] temp;
--size;
return true;
}
}
return false;
}
main:
int main()
{
DynamicStringArray dsArray1;
cout << "dsArray1.displayContents():" << endl;
dsArray1.displayContents(); // Should indicate array is empty
cout << "Display dsArray1.getSize()= " << dsArray1.getSize() << endl;
dsArray1.addEntry("Entry-A");
dsArray1.displayContents();
dsArray1.addEntry("Entry-B");
dsArray1.displayContents();
dsArray1.addEntry("Entry-C");
dsArray1.displayContents();
return 0;
}
Can anyone tell me what I am doing wrong. How can i fix this problem?
Please note that all of this is already available by utilizing
std::vector<std::string>. The std::vector class is the dynamic array class that C++ provides, and there is little to no reason to make home-made versions of what is available to you.
Having said this, one glaring issue is that your copy constructor is incorrect. The dynamicArray is uninitialized, but you use it here:
if (dynamicArray != NULL)
There is no guarantee what value dynamicArray has. The fix is to remove this entire block of code in the copy constructor:
if (dynamicArray != NULL)
{
size = 0;
delete [] dynamicArray;
dynamicArray = NULL;
}
Since the copy constructor constructs a brand new object, there is no reason to "pretest" for a NULL pointer and thus do unnecessary work. Remember that the object did not exist, so there is nothing preliminary to do.
The second issue is that you're issuing a delete [] temp; call in the addEntry and deleteEntry functions. Remove these lines, as you are deallocating the memory that you've just assigned to dynamicArray.
The third issue is that you're missing the user-defined assignment operator. The assignment operator has the following signature, and you need to provide the implementation:
DynamicStringArray& operator=(const DynamicStringArray& );
Without this function, assigning a DynamicStringArray to another DynamicStringArray will cause memory leaks and double deallocation of memory when both objects go out of scope.
One implementation can use the copy / swap idiom:
#include <algorithm>
//...
DynamicStringArray& DynamicStringArray::operator=(const DynamicStringArray& rhs)
{
DynamicStringArray temp(rhs);
std::swap(temp.dynamicArray, dynamicArray);
std::swap(temp.size, size);
return *this;
}
Another issue is this:
string DynamicStringArray::getEntry(int index)
{
if ((index >= 0) && (index < size))
{
return dynamicArray[index];
}
return NULL; // <-- Undefined behavior if this is done
}
It is undefined behavior to assign a std::string object with NULL. Either return an empty string, or throw an exception if the index is out of bounds.
In conclusion, I highly recommend that you read up on the Rule of 3 when it comes to designing classes that must implement correct copy semantics.

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.

Dynamic Memory Allocation for Objects

#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.