Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a constructor that takes variables from its base class?

I'm doing an online course which asked me to do what I wrote as the title. I did what made the code compile and give the correct output but the comment in my grading gave an error which I don't quite understand.

Here is the instruction of the assignment:

A base class Pair contains a single constructor Pair(a,b) that initializes the pair with the two integer arguments a and b. A derived class sumPair inherits the base class Pair, and specializes it with a new constructor sumPair(a,b) and a new variable sum.

Both of these classes have already been defined.

Implement the new constructor sumPair(a,b), which was declared already in class sumPair. The new constructor sumPair(a,b) should initialize the inherited class Pair with integer values a,b and set the member variable "sum" to the sum of a and b.

Now here's the code (I only wrote a few lines)

    /* Class Pair has already been
     * declared and defined with the
     * following constructor:
     *
     *   Pair(int,int)
     *
     * that stores its two arguments in
     * two private member variables of Pair.
     *
     * Class sumPair has also already been
     * defined as follows:
     *
     * class sumPair : public Pair {
     * public:
     *   int sum;
     *   sumPair(int,int);
     * };
     * 
     * Implement the constructor
     * sumPair(int,int) such that it
     * loads the two member variables of
     * the base Pair class with its
     * arguments, and initializes the
     * member variable sum with their sum.
     */

    //this is the part I wrote
    sumPair::sumPair(int a,int b){
      sum =a+b;
    }

    /* Below is a main() function
     * you can use to test your
     * implementation of the
     * sumPair constructor.
     */

    int main() {
      sumPair sp(15,16);
      std::cout << "sp(15,16).sum =" << sp.sum << std::endl;
      return 0;
    }

I get the output sp(15,16).sum =31 which I think should be correct.

The error from the grading is

The members of Pair were not properly initialized to the arguments of the sumPair constructor.

Other than that, I also tried printing things at the beginning and at the end of my constructor. Both show in the output as well, so I'm sure the constructor operated.

like image 675
Patricia Sung Avatar asked Jan 21 '26 06:01

Patricia Sung


1 Answers

You initialized sum correctly, but forgot to call up to the base-class constructor. i.e. what you want is:

sumPair::sumPair(int a,int b)
  : Pair(a, b)
{
  sum =a+b;
}

... so that the Pair(a,b) constructor will get called in the base class and set the base-class variables properly. In the code you had, the default-constructor Pair() would get implicitly called instead, and the base-class's member-variables wouldn't get set to a and b.

like image 139
Jeremy Friesner Avatar answered Jan 22 '26 20:01

Jeremy Friesner