Unable to access a protected variable in a derived class.

I'm trying to understand my following error.

Q1.cpp:27: error: ‘double Dessert::calories’ is protected
Q1.cpp:46: error: within this context


But I don't understand why I am having access rights.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <typeinfo>
using namespace std;


class Dessert
{
	public: 
	Dessert()
	{
		calories = 10;
	}
	
	void addSugar(double s)
	{ 
		calories += s*3; 
		return;
	}

	void printDetails()
	{
	cout << "Calories of " << typeid(this).name() << " is " << calories << "\n";
	return;
	}
	
	protected:
		double calories;		
};


//Add Chef class here
//1. Add constructor as specified
//2. Add isHealthy function
//3. Add member variable qualified
class Chef : public Dessert {
private:
  bool qualified;

public:
Chef() {
  qualified = true;
}

bool isHealthy(Dessert D) 
{
  if (D.calories < 300)
    return true;
  return false;
}

  friend bool checkQualifications(Chef C);

};

//Uncomment for final solution

bool checkQualifications(Chef c)
{
	return c.qualified;
}

int main()
{
  cout << "Q1 running..." << endl;
  
  Dessert d;
  
  
  //Uncomment and fix typos
  //DO NOT ADD NEW LINES or cout statements
  
  double increment;
  cout << "Input sugar increment: ";
  cin >> increment;
  int count = 0;
  Chef c;
  if(checkQualifications(c))
  {
	cout << "Chef is qualified" << endl;
	d.printDetails(); 
	while (c.isHealthy(d))
	{
		count++; //increment count
		d.addSugar(increment);
		d.printDetails();
	}
	cout << "The chef added " << count*increment << " sugar units before it became unhealthy" << endl;
  }
  
}


FYI, I can't access calories inside of Chef::isHealthy();


Another thing, I'm using public inheritance but I really do feel like I should be using protected or private inheritance since this function is essentially a "has-a" relationship. Am I correct?


ONE LAST THING: This is a practice exam. My teacher explicitly said to not use getters/accessors and to not make calories public. But I need to access calories. Is using "Friend" a possible with derived classes?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ...

class Chef : public Dessert {
private:
    bool qualified;

public:
    Chef() {
        qualified = true;
    }

    bool isHealthy()
    {
        return calories < 300;
    }

// ... 

Topic archived. No new replies allowed.