Confusingly with C ++ inheritance

I am so confused with the output of the following code:

#include <iostream>

using namespace std;

class Parent
{
public:
    Parent() : x(2) { }
    virtual ~Parent() { }

    void NonVirtual() { cout << "Parent::NonVirtual() x = " << x << endl; }

private:
    int x;
};

class Child : public Parent
{
public:
    Child() : x(1) { }
    virtual ~Child() { }

    void NonVirtual() { cout << "Child::NonVirtual() x = " << x << endl; }

private:
    int x;
};

int main()
{
    Child c;
    Parent* p = &c;

    c.NonVirtual();  // Output: Child::NonVirtual() x = 1
    p->NonVirtual(); // Output: Parent::NonVirtual() x = 2
    // Question: are there two x'es in the Child object c?
    //           where is x = 2 from (we have not defined any Parent object)?

    cout << sizeof(c) << endl;
    cout << sizeof(*p) << endl;

    return 0;
}
+3
source share
2 answers

, ++ , virtual, overriden. , , , . runtime type, , , , compile- (.. ). p Parent *, Parent, c Child, , Child. virtual, , Child.

, x... , "protected" ( , , ). x, Child, , , . , x private Parent, x Child, x Child.

+5

. , , , .

Parent * p , . , , , , .

, ( ), . , , .

, , , P P, C, .

0

Source: https://habr.com/ru/post/1756399/


All Articles