Search code examples
programming-languages

General OOP - Instantiating an interface/protocol using a class constructor/init memory usage


If you for example make a class with 100 variables and 100 functions, and an interface with 10 functions. The beforementioned class implements this interface. You then construct the class as a protocol/interface. You can only access the 10 functions.

What happens to the rest of the class that is not visible? Is it just not visible, or does it actually disappear? Does a struct behave differently in this case? Will it use more RAM if it was instantiated as a class instead?

Thanks!


Solution

  • So I'm guessing you are talking about something like this:

    class SomeInterface {
        public:
        virtual void foo();
    }
    
    class SomeClass : public SomeInterface {
        public:
        char buffer[1024];
    
        virtual void foo() override {
    
        }
    
    }
    
    SomeInterface* inter = new SomeClass();
    

    So as you mentioned, 'inter' can only access the functions of the interface, like in my example 'foo'.

    This question, I would guess varies on the programming language you are dealing with. I would guess as long as 'inter' was never casted up to 'SomeClass' or beyond, some programming languages might optomize out the instantiation of SomeClass altogether, assuming 'SomeInterface' was not pure virtual like in this instance.

    But to your question, I can answer for something like C/C++. In this example if we were to disect the memory at 'inter' it would look something like this.

    Instance of SomeInterface [0 -> sizeof(SomeInterface)]
    Instance of SomeClass [sizeof(SomeInterface) -> sizeof(SomeInterface) + sizeof(SomeClass)]
    

    This map may vary base off compiler but in the general sense, even though you don't have access to the 'SomeClass' class instance, it still exists and takes up space in memory. Some compilers may/will take up more space with type information to assist in casting, virtual function tables, and other stuff.