Using class object in another class

Im getting an error: use of undeclared identifier. I created an class with its own .h and .cpp. We'll call this ClassA and created a second class
with in its own files, we'll call this ClassB, that uses ClassA objects.
1
2
3
4
Class ClassB
{
public:
   vector<ClassA> errorHere      


Would i need to use inheritance?
Last edited on
Would i need to use inheritance?

you'd use inheritance when there is a relationship b/w the classes e.g. is-a relationships can be modelled with public inheritance, has-a relationships with private or protected nheritance etc. there are also other ways of usings object of one class in another – search containment / composition / layering in C++
a good reference is: C++ Primer Plus (5th edition) – Stephen Prata – Chapter 14 – section: Classes with Object Members
as for the little code snippet that you posted, class B needs to see the complete definition (not just declaration) of class A as you're using objects of (not pointers to) type A in B:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>

class A{};//definition of class A
//class A; //declaration of class A - will produce incomplete type error message

class B{public: std::vector<A> m_VecOfA;};

int main()
{
    B b;
    std::cout << b.m_VecOfA.size() << "\n";//prints 0
}
Last edited on
I was able to get it to work but I don't think its recognizing CardTemplate because the function is no longer working. Would forward declaration be a possible solution?
Last edited on
> Would i need to use inheritance?

No. You would need to #include "ClassA.h" before defining classB.
I was under the impression including another class.h file in another was bad practice?
Including one header in another header gratuitously is bad practice.

There are many situations where one header needs to include another header; the general rule is: if you do not need it, do not include it. For instance, in many cases, it may be sufficient if we include the header in the implementation (.cpp) file.
Topic archived. No new replies allowed.