1

I would like to know what the code which is followed by a base class constructor does. Here is the code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Person
{
public:
    Person() : name(""), age(0) {}

protected:
    string name;
    int age;
};

class Student : public Person
{
public:
    Student() : Person::Person() {}

private:
    int student_id;
};

I know what the code does in class Person:

Person() : name(""), age(0) {}

But I do not understand what this line does in class Student:

Student() : Person::Person() {}

So what it the meaning of Person::Person() after the colon?

Wubin
  • 141
  • 2
  • 11
  • 1
    This should be of use: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – eerorika May 29 '19 at 21:06

1 Answers1

2

Student() : Person::Person() {} is calling the constructor of the base class Person in the member initialization list of the derived Student constructor.

Note that Person::Person() can be simplified to just Person() in that context, as there is no need to fully qualify it using its class type.

Student() : Person() {}

You don't need to specify a base class constructor in the member initialization list of a derived constructor unless the derived constructor passes input values to the base class constructor. Which your code does not, so you can optionally omit the base class constructor call entirely. Person() is a default constructor, which the compiler will call automatically for you.

Student() {}

In which case, you can optionally also omit the Student constructor entirely, since it doesn't initialize anything else explicitly.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770