1

I am working on an assignment that involves making a class called Sub that will represent subroutines. This class will include a constructor with four arguments: name (a string), a pointer to its static parent object, number of arguments, and number of variables.

If the static parent pointer is NULL then the object does not have a parent. I am stuck on how I can pass a pointer as one of the arguments to the constructor especially if I want the pointer to be NULL in order to represent the first subroutine. This is what I have so far:

class Sub
{
public:
    Sub(); //constructor
    Sub::Sub(string sName, Sub &sParent, int sNumberofArguments, int sNumberofLocalVariables); // default constructor

private:
    string name;
    Sub * parent;
    int numberOfArguments;
    int numberOfLocalVariables;
};

...

Sub::Sub(string sName, Sub &sParent, int sNumberofArguments, int sNumberofLocalVariables)
{
    name = sName;
    parent = &sParent;
    numberOfArguments = sNumberofArguments;
    numberOfLocalVariables = sNumberofLocalVariables;
}

...

int main(){
    Sub first("first", NULL, 4, 5); //ERROR
    Sub second("second", first, 3, 6); 
}
  • 2
    Possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) –  Nov 26 '17 at 00:08

1 Answers1

1

Either make your constructor take Sub * instead of Sub &, or make an additional constructor that takes no Sub & and sets parent to nullptr internally.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Even when I change the constructor to take `Sub *` instead, these errors appear for the main: error C2664: 'Sub::Sub(const Sub &)' : cannot convert argument 2 from 'int' to 'Sub &' error C2664: 'Sub::Sub(const Sub &)' : cannot convert argument 2 from 'Sub *' to 'Sub &' – user9008895 Nov 26 '17 at 00:22
  • @user9008895: What is the line of code which triggers that error? – John Zwinck Nov 26 '17 at 00:31
  • `Sub first("first", NULL, 4, 5); ` and `Sub second("second", first, 3, 6);` – user9008895 Nov 26 '17 at 00:35
  • Please post your full, complete code with the error in your question now. The error you have written in the above comment implies you have not used my answer at all. – John Zwinck Nov 26 '17 at 01:46
  • I got it to work. It was a problem with my IDE not the code. I restarted it and the program was able to run. – user9008895 Nov 26 '17 at 15:53