0

What is considered the best practice for handling this situation?

class A {
    private:
        std::vector<B> derp;
    public:
        struct B { ... };
        void foo(B b);
}

(The problem is that this code would say "error: use of undeclared identifier 'B'" I think I could solve the problem by doing something like

class A {
    public:
        struct B { ... };
        void foo(B b);
    private:
        std::vector<B> derp;
}

But that seems strange and not like the proper solution. Also as a side note, if I were to write that should I write it like this?

struct A {
    struct B { ... };
    void foo(B b);

    private:
        std::vector<B> derp;
}
2
  • i would say to create the B class and include it later in the Class A declaration. Commented May 20, 2015 at 18:39
  • 1
    Do you ant people to be able to create instances of B or should it be something only accessible to your A? Commented May 20, 2015 at 18:44

2 Answers 2

1

You could use a forward declaration of B before declaring derp if you don't want to move the definition of B before declaring derp.

class A {
   public:
      struct B;
   private:
      std::vector<B> derp;
   public:
      struct B { ... };
      void foo(B b);
};

However, from a physical layout perspective, the public section of a class shoud be before its private section. You want the public section to be seen by a user first.

Given that, I think it'll be better to use:

class A {
    public:
        struct B { ... };
        void foo(B b);
    private:
        std::vector<B> derp;
};

That solves the problem of B not being declared/defined before the declaration of the member variable derp. It also puts the public section ahead of the private section.

Sign up to request clarification or add additional context in comments.

1 Comment

It's undefined behavior to create std::vector of incomplete type.
0

Just like variables, you can forward-declare classes and structures. For example, in your case you can do the following:

class A {
public:
    struct B;
private:
    std::vector<B> derp;
public:
    struct B { ... };
    void foo( B b );
};

Keep in mind if you forward-declare a class or structure within a class, you need to declare it with the same access level (private/protected/public) as you define it later.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.