C
C
comradegoryaev2015-01-19 22:29:08
OOP
comradegoryaev, 2015-01-19 22:29:08

Where are base class private data stored when accessed through a derived class (C++)?

Let's say we have a base class:

class A
{
public:
   int geti();
   void seti(int);
private:
   int i;
};

int A::geti()
{
return i;
}

void A::seti(int n)
{
i = n;
}

And there is a class derived from it:
class B: public A
{
    //содержимое В не важно
};

Let's say main() has the following code:
B ob;
ob.seti(10);
cout<<ob.geti();

Question: Since i is a private member of the base class, it does not exist in the derived class. Then where does 10 go in the ob.seti(10) line? The example is taken from Schildt's book "C ++ Tutorial", but I did not find the answer to my question

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
jcmvbkbc, 2015-01-19
@comradegoryaev

since i is a private member of the base class, it does not exist in the derived class

The error is here. Inheritance expresses the relation "to be": the heir is all of his parents. An object of class B is also an object of class A and contains all of its fields and methods. But not all of them have access.
The answer to your question is in section 10 Derived Classes of the C++ standard, which in the '98 revision says:
Unless redefined in the derived class, members of a base class are also considered to be members of the derived class. The base class members are said to be inherited by the derived class.

A
Armenian Radio, 2015-01-19
@gbg

Implementation details vary by compiler and platform. The standard guarantees only that the compiler will swear at an attempt to access an internal class member from outside. How the variable itself will be stored is not specified by the standard.

T
tsarevfs, 2015-01-19
@tsarevfs

Access modifiers do not affect the presentation of data at all. Roughly speaking, if in some code we replace everything private with public, nothing will change as a result of compilation. These modifiers only limit what can be used in C++ code.

L
Lolshto, 2015-01-19
@Lol4t0

Not stored anywhere. And in general, there is no i

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question