Overloaded constructor in derived class

Medvednic picture Medvednic · Jul 9, 2014 · Viewed 7.6k times · Source

I have the base class Manager and the derived class Worker, the inheritance seem to work properly - I've created a new object of the derived class using it's default constructor and i can output properly. but now I want to make an overloaded constructor for the derived class (Worker) and there seem to be a compilation error, I tired to look for an answer but I didn't found one. why the compiles says that Worker doesn't have id, name and salary fields? I've created a derived class by the book and created ctors for it.

Manager header:

#include <string>
#ifndef MANAGER_H
#define MANAGER_H

class Manager
{
public:
    Manager (); //ctor
    Manager (std::string, std::string, float, int); //overloaded ctor
    friend void display (Manager&); //friend function is declared
    ~Manager (); //dtor
protected:
    std::string id;
    std::string name;
    float salary;
private:
    int clearance;
};

Manager cpp:

#include <iostream>
#include "Manager.h"
#include "Worker.h"

Manager::Manager() //default ctor
{
id = "M000000";
name = "blank";
salary = 0;
clearance = 0;
}

Manager::Manager(std::string t_id, std::string t_name, float wage, int num): id (t_id), name      (t_name), salary(wage), clearance (num)
{
//overloaded ctor
}

Manager::~Manager()
{
 //dtor
}

Worker header:

#include <string>
#ifndef Worker_H
#define Worker_H

class Worker: public Manager
{
public:
    Worker();
    Worker (std::string, std::string, float, int);
    ~Worker();
     friend void display (Worker&); //friend function is declared
protected:
    int projects;
private:

};

#endif // Worker_H

Worker cpp:

#include <iostream>
#include "Manager.h"
#include "Worker.h"

Worker::Worker() //default ctor
{
id = "w000000";
name = " - ";
salary = 0;
projects = 0;

}
Worker::Worker(std::string t_id, std::string t_name, float wage, int num) : id (t_id), name (t_name), salary (wage), projects (num);
{
//ctor
}
Worker::~Worker()
{
//dtor
}

Answer

LearningC picture LearningC · Jul 9, 2014
 Worker::Worker(std::string t_id, std::string t_name, float wage, int num) : id (t_id), name (t_name), salary (wage), projects (num)
{
//ctor
}

here you initialize the members id,name, salary and clearance defined in base class. you need to pass it to the base class constructor for initialization. you cannot initialize them directly.
id, name and clearance are protected so you can access them in derived class but you cannot initialize them directly using initialization list. either you can initialize inside the constructor or make a call to base constructor in initialization list.

Worker::Worker(std::string t_id, std::string t_name, float wage, int num):Manager(t_id,t_name,wage,0), projects (num)
{
//ctor
}