main cannot call class functions
everytime i try to call a function from a class, the program crashes. can someone take a look and tell me what is wrong with the program?
header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#ifndef BEJEWELED_HPP
#define BEJEWELED_HPP
#include<string>
using namespace std;
typedef char T;
class bejeweled
{
public:
bejeweled();
~bejeweled();
//operation
void push_back(T item);
void pop_back();
T& operator[] (int index);
void insert(int position, T item);
void erase(int position);
int size();
int capacity();
private:
//data structure
T* array;
int size_; //number of item in array
int capacity_; //number of slot in the array
};
#endif // BEJEWELED_HPP
|
initialization:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include "bejeweled.hpp"
bejeweled::bejeweled() : array(NULL), size_(0), capacity_(64) {
}
bejeweled::~bejeweled() {
delete[] array;
array = NULL;
}
void bejeweled::push_back(T item) {
if(size_ == capacity_)
return;
else
array[size_++] = item;
}
void bejeweled::pop_back() {
if(size_ > 0)
size_--;
}
T& bejeweled::operator[] (int index) {
if (index >= 0 && index < size_)
return array[index];
}
int bejeweled::size() {
return size_;
}
int bejeweled::capacity(){
return capacity_;
}
void bejeweled::insert(int position, T item) {
if(position < 0 || position >= size_)
return;
for(int i = size_-1; i >= position; --i)
array[i+1] = array[i];
array[position] = item;
size_++;
}
void bejeweled::erase(int position) {
if(position < 0 || position >= size_)
return;
//shifting
for(int i = position+1; i < size_; ++i)
array[i-1] = array[i];
size_--;
}
|
main:
1 2 3 4 5 6 7 8
|
#include<iostream>
#include<cstdlib>
#include "bejeweled.hpp"
int main(){
bejeweled b;
b.push_back('A');
}
|
array is NULL, so how is the following supposed to not crash?
array[size_++] = item;
Topic archived. No new replies allowed.