How are subclass objects highlighted in C ++?

I have a confusion about the concept of inheritance in C ++, suppose we have a class called computer, and we publicly inherit a class called laptop from a computer class. Now that we create an object of class laptop in the main function, what happens in memory? Explain.

+3
source share
7 answers

I assume that Laptop is inherited from the computer and explains what happens at all; C ++ implementation details (for optimization reasons) may differ from this general explanation.

Logically, a laptop class definition has a pointer to a computer class definition. An instance of the Laptop class has a pointer to the definition of the laptop class (in C ++, most likely, this is just a reference to an array of function pointers for class methods).

When a laptop object receives a message, it first searches its function table for the appropriate function. If not, it follows the inheritance pointer and looks at the method table for the Computer class.

Now, in C ++, a lot of this happens at the compilation stage, in particular, I believe that the method table is smoothed out, and any calls that can be statically linked are shortcuts.

+3
source
class Computer {
  public:
   Computer() { /* whatever */}
   /* whatever */
};

class Laptop : public Computer {
   public:
    Laptop() { /* whatever */ }
  /* whatever */
};

And then...

x = new Laptop();

What the compiler implements as:

  • ptr = ::operator new(sizeof(Laptop))
  • Computer::Computer(ptr)
  • Laptop::Laptop(ptr)
  • x = ptr

I leave the stack equivalent as an exercise for the reader.

+11

, , . . Stroustrup " ", "", . super , , , , . , .

+4

, . . :

class Base()
{
public:
    virtual void foo();
    virtual void bar();
    void hello();

private:
    int variable1;
};

class Derived : public Base
{
public:
    virtual void foo();
    virtual void bar();
    void bye();

private:
    float variable2;
};

( : .)

:

/*
Base object layout:
[vftable pointer]   (points to the 1st row in the virtual function table)
[int variable1  ]   (from Base)

Derived object layout:
[vftable pointer]   (points to the 2nd row in the virtual function table)
[int variable1  ]   (inherited from Base)
[float variable2]   (from Derived)

virtual function table layout:
[&Base::foo   ] [&Base::bar   ]
[&Derived::foo] [&Derived::bar]
*/

, Base Derived . Derived. Derived "" .

, hello() bye() vf, . .

Wikipedia , , .

Uni , , .

C, .

+4

:

class Computer {
    char manufacturer[20];
    char type[10];
}

class Laptop : Computer {
    int runningTime;
}

computer, 20 + 10 = 30 . , 4 , - 4 = 34 . , , . ( ..) :

i.g.

Laptop lap = new Laptop();
+2

Memory is allocated for placement sizeof (object). This includes any primitives, such as int, char, etc. that can be inherited. May be on the heap / stack.

-1
source

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


All Articles