Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a derived class be smaller than its parent class?

I'm asking this about C++ since I'm familiar with that but the question really explains itself: is there a language in which we can derive a class and make it occupy less space in memory than the original class?

This question is more of a gimmick than an actual problem I'm trying to solve, but I could imagine that some really high-performant code could benefit from this kind of memory optimization:

Suppose we have:

class Person {
    std::string name;
    unsigned int age;
}

class PersonNamedJared {
}

In theory, we don't need a field "name" in this subclass since it'll always be "Jared", which could allow for better memory efficiency.

Is the only way to make this happen by replacing the 'name' field in Person with a get_name() function that we simply override in PersonNamedJared to always return "Jared"? How would we still make the name variable in the base class?

I know this example is really bad practice, but it's the best I could come up with. I think there are legitimate reasons to implement this kind of pattern.

like image 316
Adriaan Jacobs Avatar asked Dec 17 '22 13:12

Adriaan Jacobs


1 Answers

Can a derived class be smaller than its parent class?

No. A derived class always contains a base class sub object. An object can never be smaller than its sub objects, so a derived class can never be smaller than its base.

Is the only way to make this happen by replacing the 'name' field in Person with a get_name() function that we simply override in PersonNamedJared to always return "Jared"?

That would be one way to achieve it.

How would we still make the name variable in the base class?

You couldn't have a member variable in a base that you don't want to be in the derived class.

You could for example use multiple inheritance so that you do have a base with the variable in some derived classes. Something like this:

struct Person {
    unsigned int age;
    virtual std::string name() = 0;
    ...

struct Named {
    std::string name;
};

struct NamedPerson : Person, private Named {
    std::string name() override {
        return name;
    }
};

struct JaredPerson : Person {
    std::string name() override {
        return "Jared";
    }
};

Here, there is a base with the variable, but Jared does not inherit that particular base.

like image 107
eerorika Avatar answered Dec 29 '22 08:12

eerorika