Classes

Hi,

I am working on the question below.

Consider the following class declaration:
1
2
3
4
5
6
7
8
9
10
11
class Employee
{
public:
Employee ();
string getName();
private:
bool citizen();
string lastName;
string firstName;
string employeeNumber;
};


Explain what is wrong with the following code fragment:
1
2
3
4
5
6
7
int main()
{
Employee e;
……
string eNumber = e.employeeNumber;
return 0;
}


I have attempted to merge the 2 pieces of code with omitting the ......, but this errored out as there was no:
#include <iostream>
#include <string>
using namespace std;

so i have added these in to have the code below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

class Employee
{
public:
Employee ();
string getName();
private:
bool citizen();
string lastName;
string firstName;
string employeeNumber;
};

int main()
{
Employee e;
string eNumber = e.employeeNumber;
return 0;
}


which at line 15 I receive:
error: 'std::string Employee::employeeNumber' is private'
and at line 21:
error: within this context

Could anyone help with the detail that the instructor would be looking for to answer this question as I don't think that the extracts from the line errors above is what is expected.

Thanks again.
Last edited on
closed account (zb0S216C)
"Employee::employeeNumber" is private. In general, private data-members cannot be read from or written to by a function or class that's neither a friend class, friend function or member-function.

You have a few choices to overcome this problem:

1) Friends. A friend of a class is either a function or another class that's allowed to read or write to private data-members directly. Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
class Something
{
  int X;

  public:
    friend int ReadXFromSomething( Something &Object );
};

int ReadXFromSomething( Something &Object )
{
  return( Object.X );
}

Here, "ReadXFromSomething( )" is a friend of "Something" and is allowed direct access to the data-members of another "Something" object.

2) Getters. Getters are the counterpart of setters. Getters obtain the value of a data-member. It's common practice (and preferred) for getters member-functions to return either a non-constant copy or a constant reference to some data-member.

1
2
3
4
5
6
7
8
9
10
11
class Something
{
  private:
    int X;

  public:
    int GetXCopy( ) const
    {
      return( X );
    }
};

Here, "Something::GetXCopy( )" is a getter. Note the "const" qualifier; it's used to tell the compiler that the data-members will not be modified during the call to "Something::GetXCopy( )". It's common for getters to be declared this way.

Both of the above solutions respect the encapsulation concept when applied correctly. Please, in the future, avoid setters at all costs.

Wazzak
Last edited on
Topic archived. No new replies allowed.