Alcott
Alcott

Reputation: 18585

nested class or struct in a class

Code goes first:

//.h file

class A
{
    public:
        A();
        B makeB(int);  //question 1
    //protected:
        struct B {
            int _id;
            B(int id);
        }
};

//.cpp file

A::A()
{  cout<<"A ctor\n"; }

B A::makeB(int id)  //question 2
{  return B(id); }

2 questions:

1.Should I put makeB() function after the definition of struct B?

2.In .cpp file, should prefix every B with A:: ?

PS: 1.If makeB function doesn't deal with B instances, but B pointers or refs, can I put a forward decl of struct B in front of makeB? (I just don't want put the definition of struct B in front of mem-funcs).

Upvotes: 1

Views: 1383

Answers (3)

robermorales
robermorales

Reputation: 3488

Q1. Yes (it needs to know the size of struct B)

QPS1. Yes (if it only uses pointers to B, it does not need to know the size)

Q2. Also, you can write "using A::B" and then, use "B" as usual.

Upvotes: 1

duedl0r
duedl0r

Reputation: 9424

This compiles fine:

class A
{
 public:
    struct B;

    A();
    B makeB(int);  //question 1

    struct B {
        int _id;
        B(int id) {};
    };
};

A::A() {}

A::B A::makeB(int id)  //question 2
{  return B(id); }

Upvotes: 2

arne
arne

Reputation: 4674

Yes and yes. Otherwise, this should be hard to compile.

Upvotes: 0

Related Questions