I am trying to create a class for doing number factorization on a random number, so I need to create a pointer to store the factors of the number. But when I compiled it, I got an error. My question is 1)What did I do wrong? I have a feeling I did something wrong with the initialization, but I just couldn't pinpoint what the problem is. 2) Is there a better way to store a set of numbers beside using member pointer? for example, a member array. :)

Output:
1
2
3
t.cpp: In constructor 'numFactor::numFactor(int, int*)':
Line 14: error: expected identifier before '*' token
compilation terminated due to -Wfatal-errors.

#include <iostream>
#include <ctime>
using namespace std;

class numFactor{
protected:
int *factorPtr;
int factorSize;
int inputNum;

public:
//Constructor
numFactor(int num=0, int *ptr=NULL)
:inputNum(num),*factorPtr(&ptr)
{}

//Mutator
void setinputNum(){inputNum=2+rand()%98;}
void setfactorPtr();

//Accessor
int getinputNum(){return inputNum;}
int* getfactorPtr(){return factorPtr;}
int getfactorSize(){return factorSize;}

//Display
void printinputNum();
void printfactorPtr();
};

void numFactor::setfactorPtr()
{       
        // Find factors and put it in a stack
         stack<int> factorStack;
	 for(int i = 2; i < number; i++) // Test for factors > 1
	 {
		 if(number % i == 0) // It is a factor > 1
		 {
			 bool factor = true;
			 if(factor)
				 factorStack.push(i);
		 }
	 }

        //store the size of the factor
        factorSize=(int) factorStack.size();         

        // Store the stack in a pointer;
         *factorPtr=new int[factorSize];
         for(int i=0;i<factorSize;i++)
         { *(factorPtr+i)=factorStack.top();
           factorStack.pop();
          }
}

void numFactor::printinputNum()
{ cout<<"The input number is "<<inputNum<<endl;
}

void numFactor::printfactorPtr()
{ cout<<"The factor(s) is/are "
  for(int i=0; i<factorSize;i++)
  { cout<<*(factorPtr+i)<<"  ";}
  cout<<endl;
}

int main()
{ srand((unsigned) time(0));
  numFactor test;
  test.setinputNum();
  test.setfactorPtr();
  test.printinputNum();
  test.printfactorPtr();

return 0;
}

The error message itself says where you went wrong.Initialization of factorPtr in line 14 should be factorPtr(ptr) rather than *factorPtr(&ptr).

Edited 5 Years Ago by csurfer: n/a

I made the modification you suggested, but it didn't seem to help. Here are the output after modification.

Output:
1
2
3
4
5
6
7
8
cc1plus: warnings being treated as errors
t.cpp: In constructor 'numFactor::numFactor(int, int*)':
Line 9: warning: 'numFactor::inputNum' will be initialized after
Line 7: warning: 'int* numFactor::factorPtr'
Line 13: warning: when initialized here
t.cpp: In member function 'void numFactor::setfactorPtr()':
Line 35: error: 'number' was not declared in this scope
compilation terminated due to -Wfatal-errors.

This question has already been answered. Start a new discussion instead.