Search code examples
c++classpointersobjectsubroutine

Passing a class object pointer to default constructor (C++ Subroutines)


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); 
}

Solution

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