-2

A little weird prob;em i came across when working on something that I got stuck with and I have no idea why this happens.

So i have 2 files (actually way more but those arent important) called Employee and Keeper. Employee is the base class while Keeper is the derived class.

The employee has several attributes and a method called saveFile and the keep inherits these.

Employee.h:

protected:

    const int           number;
    const std::string   name;
    int                 age;

    // All ordinary employees
    Employee            *boss = nullptr;            // works for ...

public:
    void saveFile(std::ostream&) const;

Keeper.cc

void Keeper::saveFile(ostream& out) const
{
     out << "3\t3\t" 
     << number << "\t" << name << "\t" << age 

     // The error happen here on boss->number
     << "\t" << cage->getKind() << "\t" << boss->number << endl;
}

Keeper.h (full code)

#ifndef UNTITLED1_KEEPER_H
#define UNTITLED1_KEEPER_H

#include "Employee.h"
// tell compiler Cage is a class
class Cage;
#include <string>   // voor: std::string
#include <vector>   // voor: std::vector<T>
#include <iostream> // voor: std::ostream

class Keeper : public Employee {
    friend std::ostream& operator<<(std::ostream&, const Keeper&);

public:
 Keeper(int number, const std::string& name, int age);

~Keeper();
/// Assign a cage to this animalkeeper
void setCage(Cage*);

/// Calculate the salary of this employee
float getSalary() const;

/// Print this employee to the ostream
void print(std::ostream&) const;

// =====================================
/// Save this employee to a file
void saveFile(std::ostream&) const;
protected:

private:
    // Keepers only
    Cage *cage = nullptr;           // feeds animals in ...
};

Now i get the error on the const int number from the employee.h when i call boss->number in the saveFile method.

The error is on this line:

 << "\t" << cage->getKind() << "\t" << boss->number << endl;

because of boss->number

I have no idea why this happens and everywhere I read it said it should compile just fine but it doesnt.

Can anyone help?

Thank you~

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Ellisan
  • 563
  • 8
  • 22

1 Answers1

1

The number member of the boss object is protected from direct access by functions outside of the object itself, even when owned by an object of the same type. The exceptions would be friend classes and methods, and copy constuctors.

In response to a comment: Inheritance is not your problem. The data in the object itself is protected from outside access. Your Keeper object inherits its own number member that it can access, as well as a pointer to a boss Employee. To fix your problem you can either make number public, or add an access method to return the value.

Mikel F
  • 3,567
  • 1
  • 21
  • 33