I am working with a class I created that has a function addClass which allow the user to add A an Instance of Class to a dynamically allocated array.
Here is the code of the class and a simple test:
Class.h Listing
#ifndef CLASS_H
#define CLASS_H
#include<iostream>
class Class {
public:
Class(std::string text);
Class(const Class& orig);
virtual ~Class();
Class(std::string text, Class * name, int size);
std::string toString();
void addClass(Class * name, int size = 1);
Class getClass(int index);
private:
Class * classArray;
std::string value;
int size;
};
#endif /* CLASS_H */
Class.c Listing
#include "Class.h"
#include <cstdlib>
Class::Class(std::string text) {
classArray = NULL;
value = text;
size = 0;
}
Class::Class(const Class& orig) {/*...*/}
Class::~Class() {}
Class::Class(std::string text, Class * name, int size){
value = text;
this->size = size;
if(size == 1)
classArray = name;
else{
int i;
classArray = (Class*)malloc(size*sizeof(Class));
for(i = 0; i < size; i++){
classArray[i] = name[i];
}
}
}
std::string Class::toString(){
return value;
}
void Class::addClass(Class * name, int size){
int i;
Class * tmp = (Class*)malloc((this->size+size)*sizeof(Class));
for(i = 0; i < this->size-1; i++){
tmp[i] = classArray[i];
}
if(size == 1)
tmp[size-1] = name[0];//assignement method is the problem!!!??
else{
for(i = this->size; i < this->size+size-1; i++){
tmp[i] = name[i];
}
}
this->size += size;
free(classArray);
classArray = tmp;
}
Class Class::getClass(int index){
return classArray[index];
}
test.c Listing
#include<iostream>
#include "Class.h"
using namespace std;
int main(int argc, char** argv) {
Class * objectA = new Class("objectA");
Class * objectB = new Class("objectB");
cout << objectA->toString() << endl;
objectA->addClass(objectB);
//never gets here :'(
cout << objectA->toString() << endl;
return 0;
}
The problem is the test never gets past the objectA->addClass(objectB) instruction. I tried to debug and what I found was that the problem comes from the assignement instruction of the addClass() method. I also tried memcpy it didn't work. Does anyone have a solution for this please. Thanks.