C++: Can a struct inherit from a class?

后端 未结 9 957
执笔经年
执笔经年 2020-12-07 14:39

I am looking at the implementation of an API that I am using.

I noticed that a struct is inheriting from a class and I paused to ponder on it...

First, I d

相关标签:
9条回答
  • 2020-12-07 15:05

    In C++

    struct A { /* some fields/methods ... */ };
    

    is equivalent to:

    class A { public: /* some fields/methods ... */ };
    

    And

    class A { /* some fields/methods ... */ };
    

    is equivalent to:

    struct A { private: /* some fields/methods ... */ };
    

    That means that the members of a struct/class are by default public/private.

    Using struct also changes the default inheritance to public, i.e.

    struct A { }; // or: class A { };
    class B : A { };
    

    is equivalent to

    struct A { }; // or: class  A { };
    struct B : private A { };
    

    And the other way around, this

    struct A { }; // or: class A { };
    struct B : A { };
    

    is equivalent to:

    struct A { }; // or: class A { };
    class B : public A { };
    

    Summary: Yes, a struct can inherit from a class. The difference between the class and struct keywords is just a change in the default private/public specifiers.

    0 讨论(0)
  • 2020-12-07 15:05

    A class will not publicly inherit from a struct. A struct will publicly inherit from a class or a struct.

    class A
    {
    public:
        int a;
    };
    struct B : A
    {};
    

    B b; b.a=5; //OK. a is accessible

    class A
    {
    public:
        int a;
    };
    struct B : public A
    {};
    

    It means the same. B b; b.a=5; //OK. a is accessible

    struct A
    {int a;};
    class B : A
    {};
    

    B b; b.a=5; //NOT OK. a is NOT accessible

    struct A
    {int a;};
    class B : public A
    {};
    

    B b; b.a=5; //OK. a is accessible

    Finally:

    class A
    {int a;};
    class B : A
    {};
    

    B b; b.a=5; //NOT OK. a is NOT accessible

    class A
    {int a;};
    class B : public A
    {};
    

    B b; b.a=5; //NOT OK. a is NOT accessible

    0 讨论(0)
  • 2020-12-07 15:06

    Yes. Struct can inherit from a class and vice versa. The accessibility rule is

    $11.2/2- "In the absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class."

    EDIT 2: So you can change your class as:. Note that it is a bad idea to have public data members usually.

    class user_messages {  // i also changed the name when OP was modified :)
    public:   
       std::list<std::string> messages;  
    };
    
    0 讨论(0)
提交回复
热议问题