Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the derived class inherit the private members of the base class? [duplicate]

Tags:

c++

I know that the derived class can't access the private members of the base class, so why does the derived class inherit the private members of the base class? Is there any case that it is useful?

Thanks!

like image 562
skydoor Avatar asked Jan 06 '10 21:01

skydoor


4 Answers

The derived class needs the private members even though it can't access them directly. Otherwise it's behavior would not build on the class it is deriving from.

For example, pretend the private stuff is:

int i;

and the class has a geti() and seti(). The value of i has to be put somewhere, even if it is private,

like image 192
Richard Pennington Avatar answered Nov 19 '22 09:11

Richard Pennington


The public and protected methods of the base class can still access private variables of the base class, and these methods are available in the derived class.

like image 44
uncleO Avatar answered Nov 19 '22 09:11

uncleO


The base class can still use the private member variables & methods.

If you want the derived classes to have access to members but keep those members hidden from the outside world, make them protected:.

Here's an example to illustrate:

class Base
{
public:
  Base() : val(42.0f) {};
  float GetValue() const 
  {
    return val_;
  }
private:
  float val_;
};

class Derived : public Base
{
public:
  float ComputedValue() const
  {
    return GetValue() * 2.0f;
  } 
};
like image 4
John Dibling Avatar answered Nov 19 '22 08:11

John Dibling


Don't forget that the base class may have methods that are not private, and thus accessible by the derived class. Those protected or public base class methods can still invoke the private base class methods. This is particularly useful if you want to lock down core functionality in the base class, such as with a Template Method design pattern implementation:

class base
{
public:

  virtual ~base() { /* ... */ }

  virtual void base_func() { foo_private (); }
  virtual void do_func() = 0;

private:

  void foo_private()
  {
    // pre-do_func() operations

    do_func();

    // post-do_function operations
  }

};

class derived : public base
{
public:

  void derived_func() { base_func(); }

  virtual void do_func()
  {
    // Derived class specific operations
  }
};
like image 4
Void Avatar answered Nov 19 '22 08:11

Void