Xiufen Xu Xiufen Xu - 2 months ago 11
C++ Question

The way to create object of a class

I am wondering what is the difference between the following ways to create object of class. The head file is:

class NumberRange {
NumberRange(int a, int b);
virtual ~NumberRange();
void Print(int a, int b);
int *range_;
int size;

The .cc file is:

#include <iostream>
#include "numberrange.h"
using namespace std;

NumberRange::NumberRange(int a, int b) {
if (a > b) {
cout << "a must be equal or less than b" << endl;

NumberRange::~NumberRange() {


void NumberRange::Print(int a, int b) {
this->size = b - a + 1;
this->range_[0] = a;
for (int i = 0; i < this->size; i++) {
this->range_[i] = a + i;
cout << this->range_[i] << endl;

int main() {
NumberRange * numberrange = new NumberRange(5, 9);
numberrange->Print(5, 9);

When I create an object using pointer and compile the program. I got an error says
[1] 20346 segmentation fault ./numberrange

but if I change the main function as:

int main() {
NumberRange numberrange(5,9);

This would be work. So I don't know when should I use pointer to create an object. Thank you!


There are at least three problems with your program.

The first, most obvious problem is that int *range_ is a pointer to integer, but doesn't point to anything in particular. It just contains a random memory address. To change that, assign array of int to it, that you created with new, e.g. :

range_ = new int [b - a];

The second, less obvious problem is that you pass a and b two times to your object, first in the constructor and later in the Print method (better not capitalize methods, by the way). One of the things the ++ in C++ offers you is object orientation. Objects have state. If you want objects of class NumberRange to store numbers from 3 upto 7, use your constructor to store them as attributes. No need to pass that boundaries again in the Print method, it can read them from the attributes.

The third, even less obvious problem, is that in your example there's no need to store the numbers at all, since you just want to print them.

Problem two and three are connected. Probably you want to do more with your numbers than just print them. So have the constructor either store a and b, or allocate an array and store the numbers from a upto b. The latter is less efficient, but maybe later on you want to store sequences which are not adjacent integers.