0

When inheritance, do the variables in the base class get copied into the derived class? how the architecture of the child class would be?

{
public:
 int m_id;

 Base(int id=0)
     : m_id(id)
 {
 }

 int getId() const { return m_id; }
};

class Derived: public Base
{
public:
 double m_cost;

 Derived(double cost=0.0)
     : m_cost(cost)
 {
 }

 double getCost() const { return m_cost; }
};

does m_id get copied into derived while derived object's instantiation ?

slah Omar
  • 45
  • 1
  • 4
  • 6
    Nothing gets "copied" anywhere. The base class is a part of the derived class. – Sam Varshavchik Jun 30 '20 at 13:44
  • 1
    Does this answer your question? [C++: Construction and initialization order guarantees](https://stackoverflow.com/questions/2517050/c-construction-and-initialization-order-guarantees) – underscore_d Jun 30 '20 at 14:06
  • @underscore_d yes it's useful but I still did not get an appropriate answer, thank you – slah Omar Jun 30 '20 at 15:14

1 Answers1

0

The derived class (Derived) is not copying the base class (Base) in a strict sense. Derived is inheriting from Base therefore Base is part of Derived. Think of Derived extending Base with new methods and new members.

In your example, Base has a default constructor because the first parameter is an optional parameter (Base(int id=0), you can call the constructor without any arguments to set id to 0).

When you use inheritance, Derived must always call Base's constructor in Derived's constructor before doing anything else (to make sure Base's variables are initialized). However, because Base has a default constructor, the compiler does so magic to make this optional.

If you want to call a specific Base's constructor from Derived's constructor you can do the following:

Derived(double cost=0.0) : Base(1 /* or whatever you want it to be */)
{
  m_cost = cost;
}
Luke
  • 565
  • 5
  • 19
  • so how the Derived class is stored in memory with the base portion? because while Derived object instantiation, if you try to print the address of object Base in its constructor (std::cout< – slah Omar Jun 30 '20 at 14:35
  • @slahOmar They are _the same object_, so of course they have the same address. To simplifiy, the base members basically exist 'above' the derived members in memory, but they're part of the derived object. – underscore_d Jun 30 '20 at 15:16