In C++, why struct is in fact class?

后端 未结 6 660
谎友^
谎友^ 2021-01-05 11:13

The other topic and responses there made me ask this question:

Why does C++ allow struct to behave just like class? At one hand, C++ made

6条回答
  •  Happy的楠姐
    2021-01-05 11:29

    Allowing something you declare as struct to really be a class allows type-safety when creating a C interface.

    You can forwardly declare your struct for your C interface:

    struct Foo;
    

    You can declare methods on it

    void doStuffThatModifiesFoo( struct Foo * foo, ... );
    struct Bar getStuffFromFoo( const struct Foo * foo );
    

    You can also write create and destroy methods for it.

    Underneath you implement Foo not as a C struct but as a class but your C clients do not need to know that. This is better than passing it around as a void * then casting (not safe if someone passes you a void* to a completely different type and you cast it).

提交回复
热议问题