Question

So private members in the base class are also in the inherited class but not accessible in it, right?
Are they actually in the memory allocated to the the inherited object?

Was it helpful?

Solution

Are they actually in the memory allocated to the the inherited object?

Yes, they need to exist. The private members are part of the implementation detail of the base class. Without them, in general, the base class wouldn't be able to function (which is why they exist in the first place).

Making them private just allows the base class to create its implementation however it chooses, without exposing that to anybody, including the subclass.

OTHER TIPS

Yes. Just for example, you can use a public function from the base class that manipulates private data, even in an instance of the derived class:

class Base { 
    int x;
public:
    Base() : x(0) {}
    void inc() { ++x; }
    void show() { std::cout << x << "\n"; }
};

class Derived : public Base { 
};

int main() { 
    Derived d;
    d.show();
    d.inc();
    d.show();
}

With a properly functioning compiler, this must display:

0
1

...showing that the data in the Base object is present in the Derived object, even though it's not (directly) accessible.

Of course with almost anything in C++, there's the "as-if" rule -- if the compiler can determine that it can somehow produce the correct observable behavior for the program, even without including the private part(s) of the base class, then it's free to do so. The most obvious example of this would be if you included something (member function or data) in the base class that was simply never used in practice.

Yes they are,

When object of the derived class is being constructed all of its base classes are first being constructed as well.

Consider this example:

class Base
{
 int x;

 public:
  Base(int px)
   : x(px)
  {
  }
};

class Derived : public Base
{
 int y;
public:
  Derived(int px, int py)
   : y(py), Base(px)
  {
  }
};

This example compiles and works and Base is initialized (constructor is called) before you reach the body of the Derived constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top