Inheritance Flashcards

1
Q

how does the compiler solve which function to call when you have derived class object calling its members function?

A

When a member function is called with a derived class object, the compiler first looks to see if that member exists in the derived class. If not, it begins walking up the inheritance chain and checking whether the member has been defined in any of the parent classes. It uses the first one it finds.

https://www.learncpp.com/cpp-tutorial/11-6a-calling-inherited-functions-and-overriding-behavior/

class Base
{
protected:
    int m_value;
public:
    Base(int value)
        : m_value(value)
    {
    }
    void identify() { std::cout << "I am a Base\n"; }
};
class Derived: public Base
{
public:
    Derived(int value)
        : Base(value)
    {
    }
};
int main()
{
    Base base(5);
    base.identify();
    Derived derived(7);
    derived.identify();
return 0; }

When derived.identify() is called, the compiler looks to see if function identify() has been defined in the Derived class. It hasn’t. Then it starts looking in the inherited classes (which in this case is Base). Base has defined an identify() function, so it uses that one. In other words, Base::identify() was used because Derived::identify() doesn’t exist.

This means that if the behavior provided by a base class is sufficient, we can simply use the base class behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

if a function is defined as private in base class and it is redefined in derived class as public will the function be private or public??

A

Note that when you redefine a function in the derived class, the derived function does not inherit the access specifier of the function with the same name in the base class. It uses whatever access specifier it is defined under in the derived class. Therefore, a function that is defined as private in the base class can be redefined as public in the derived class, or vice-versa

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What a derived class inherits or doesn’t inherit?

A

Inherits:
Every data member defined in the parent class (although such members may not always be
accessible in the derived class!)

Every ordinary member function of the parent class (although such members may not always be
accessible in the derived class!)
The same initial data layout as the base class

Doesn’t Inherit :
The base class’s constructors and destructor.
The base class’s assignment operator.
The base class’s friends

How well did you know this?
1
Not at all
2
3
4
5
Perfectly