30

Given this base class:

class Employee
{
     char* name;
     int age;

  public:
     Employee(char* name);
     void print();
};

With regards to the "public", what's the difference between this:

class Manager : public Employee
{
   EmployeeList employees;

   public:
     Manager(char* name, Employee* people);
     void print();
};

and this:

class Manager : Employee
{
   EmployeeList employees;

  public:
     Manager(char* name, Employee* people);
     void print();
};
  • 4
    Use std::string over char*, and std::vector over a pointer-to-array. – GManNickG Oct 14 '09 at 01:07
  • 4
    I disagree. std::string adds a layer of overheads to allow variable length data. You should consider your needs and choose wisely. – sep Oct 14 '09 at 01:11
  • 2
    Without a good knowledge of the context, advices to use 'std::vectors' instead of C-arrays and 'std::string' instead of C-strings have very little value, if any. – AnT stands with Russia Oct 14 '09 at 01:13
  • 1
    @sep If the string shouldn't be dynamic, then it should have been `const char*`. @Andrey It's pretty clear that Manager is taking a pointer to an array of Employees. If not a `vector`, a `list`. – GManNickG Oct 14 '09 at 01:15

3 Answers3

52

The default is private inheritance. take this example:

class B { };
class D: B { };

uses private inheritance as its the default. This means that D gets all the protected and public fields and methods that B has (if we actually declared any), but can't be cast to a B. Therefore, this code fails:

void foo(B* argument) {}
foo(new D);                   //not allowed

If D publicly inherited from B, then a D could be cast to a B, and this function call would be fine.

The second difference is that all the protected and public members in B become private members in D.

What does this actually mean? Public inheritance means D IS_A B, but private inheritance means "is implemented in terms of". Inheriting D from B means you want to take advantage of some of the features in B, but not because D IS_A B or because there's any conceptual connection between B and D. :D

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
3

Without that 'public' 'Employee' would become a private base class of 'Manager'.

Classes declared with keyword 'class' have their members private by default, and have their base classes private by default.

Classes declared with keyword 'struct' have their members public by default, and have their base classes public by default.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

In C++, inheritance is private by default. However, to any code using the Manager class, there appears to be almost no difference, since they have the same methods.

You won't be able to cast the Manager object to an Employee, though. You also won't be able to access the employees variable from within the Manager class.

Smashery
  • 57,848
  • 30
  • 97
  • 128