0

When I run this code, the name and salary variables are never set using the derived class "Programmer", even though it passes the variables through the parent class' constructor as suggested here. No errors are being given, but the name and salary variables just don't seem to get set for some reason.

#include <string>
#include <iostream>


using namespace std;


class Employee 
{
public:
   Employee();
   Employee(string employee_name, double initial_salary);

   void set_salary(double new_salary);
   double get_salary() const;
   string get_name() const;
private:
   string name;
   double salary;
};


Employee::Employee()
{  
   salary = 0;
}

Employee::Employee(string employee_name, double initial_salary)
{  
   name = employee_name;
   salary = initial_salary;
}

void Employee::set_salary(double new_salary)
{  
   salary = new_salary;
}

double Employee::get_salary() const
{  
   return salary;
}

string Employee::get_name() const
{  
   return name;
}

class Programmer : public Employee {
public:
    Programmer(string name, double salary);
    string get_name();
private:
};

Programmer::Programmer(string pname, double psalary)
{
    Employee(pname, psalary);
}

string Programmer::get_name()
{
    return Employee::get_name();
}

int main() {
    Programmer harry("Hacker, Harry", 10000);
    cout << harry.get_name();
    return 0;
}

This question wasn't the same as my problem from what I could tell. Though that one was much more complex.

It seems like a simple logic error, I just can't find it.

Community
  • 1
  • 1
Logan
  • 143
  • 1
  • 7

2 Answers2

0

You have to use a member initializer list to initiate base class. With your constructor, you create a tempoarary Employee in the function body.

Programmer::Programmer(string pname, double psalary)
  : Employee(pname, psalary)  
{}
erlc
  • 652
  • 1
  • 6
  • 11
  • Okay, I see the big difference there. If you don't mind helping out with the understanding, is that difference in structure because it's a constructor? – Logan May 13 '15 at 05:59
  • Yes, constructors have member intializer lists (: followed by a comma separated list of initializations of base classes and members) to initialize its bases and members before the start of the function body. – erlc May 13 '15 at 06:03
0
Programmer::Programmer(string pname, double psalary)
{
    Employee(pname, psalary);
}

is equivalent to:

Programmer::Programmer(string pname, double psalary) :
   Employee()
   // Base class is initialized using the default constructor.
{
    Employee(pname, psalary);
    // Create a temporary Employee and discard it.
}

To pass name and psalary to initialize the base class, you'll need to use:

Programmer::Programmer(string pname, double psalary) :
   Employee(pname, psalary)
   // Base class is initialized using the constructor
   // that takes name and salary as arguments.
{
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270