TheNewbieProgramer
TheNewbieProgramer

Reputation:

Inheritance or Struct into Struct

I wonder what's the difference between:

struct A
{
  struct B{};
};

and:

struct A{};

struct B:A{};

Upvotes: 0

Views: 56

Answers (2)

Ivan
Ivan

Reputation: 1455

In addition to @asmmo answer:

The inheritance can have different visibilities (public, private or protected). The declaration is (only using the key word):

struct A{};

struct B: public A{};

If you don't specify it, the inheritance will be private. What does this mean?

If:

struct A{
void func(){}
};

struct B: public A{};

Any object of type B can call the function func() with b.func(); If it is private you can only call func() inside the definition of B but B-typed objects can't call it. If it is protected you can only call func() inside the definition of B and structs that inherit from B, but not their instances.

So, if your are testing inheritance, you may start doing them all public and then get more specific when needed.

Upvotes: 0

asmmo
asmmo

Reputation: 7100

In the first snippet B is nested struct in A, hence if you need to creat objects out of them you should do as follows

A a;//A object
A::B b;//B object

In the second snippet B inherits from A, hence if you need to creat objects out of them you should do as follows

A a;//A object
B b;//B object

and in the second case all of A members (if there are) will be members of B too because A is the base struct.

Upvotes: 1

Related Questions