Search code examples
c++inheritanceconstructorderived-class

C++ Derived class constructors


Say i have a class representing the subscribers for a library. I then want to create multiple other derived classes representing different types of subscribers such as students, professors etc..

  1. How do i write the derived class constructor ? In my base class Subscriber I have the constructor which takes parameters such as name,age,id number etc.. However in my derived classes I have extra parameters such as "schoolName" for example. How do I setup the constructor for the derived class Student knowing that i want to call the base class constructor of Subscriber and also add a value to an extra parameter that being schoolName.

  2. Also my second question. Would it be preferable to make the shared parameters such as age,name etc (that both the base class and the derived class share) protected as apposed to private ? That way a student can access his name,age easily


Solution

    1. Base class constructor:

    Subscriber(const char *name, int age);

    Derived class constructor:

    Student(const char *name, int age, const char *sName)
      :Subscriber(name, age) // We call the base class constructor
    {
        // Do something with sName.
    }
    
    1. It depends on what you would like to achieve, but generally it is preferred to keep the parameters as private. In this way there's less coupling between the classes, and if you need access to the parameters of the base class you can use the getter-setter approach.