Classes as members of other classes

Aug 27, 2010 at 6:22pm
I'm sure this is possible, I just do not know how to do it. I want to have a class of mine to have members that are of another class. The constructors of the other class take 3 arguments. If I try something like:

1
2
3
public:
    MyObject obj1(arg1, arg2, arg3);
    MyObject obj2(arg1, arg2, arg3);


It does not work, as that is the syntax for function prototypes. My question is how do I go about creating those objects as members of another class?
Aug 27, 2010 at 6:37pm
1
2
3
4
5
6
7
8
9
class A{...};
class B{
   public:
    B b, bb;//declare members

    B() // constructors are called here
        : b(...), bb(...) {
    }
};
Aug 27, 2010 at 7:03pm
Um, I'm not sure you understand my issue.

Let me further explain. Let's say I have two classes MyObject1 and MyObject2. I have MyObject1 to have members of type MyObject2.

In your code, B just have members of itself, or so it seems. If I'm wrong, let me know. Also note, I'm still learning quite a bit about C++ and there are many concepts I don't know yet.
Aug 27, 2010 at 7:09pm
Yes, you can have a class A which has its member of class B

class B
{
...
};

class A
{
B b;
}

But I am not sure about the conditions like :
What would happen if class B has static members
Somebody please tell me about that.

Last edited on Aug 27, 2010 at 7:10pm
Aug 27, 2010 at 7:34pm
I know it's possible. But I have constructors that take arguments. For instance, I have class A and class B. Class B looks like:

1
2
3
4
class B {
    public:
        B(double, double, double);
};


In class A, I want 2 B members. But I'm not sure how to construct them, as this:

1
2
3
4
5
class A {
    public:
        B bOne(4.5, 6.0, 9.7);
        B bTwo(3.6, 1.3, -7.3);
};


Does not work. That syntax used when trying that is the syntax for function prototypes. My question is how, then, would I create the B objects?
Aug 27, 2010 at 7:36pm
ah. sorry. I wasn't paying attention when I wrote that.
I meant
1
2
3
4
5
6
7
8
9
class A{...};
class B{
   public:
    A a, aa;//declare members

    B() // constructors are called here
        : a(...), aa(...) {
    }
};

The way I wrote it is not possible as it would result in an object of infinite size.
Aug 27, 2010 at 7:39pm
That worked =)

Thank you. I knew it was possible, just didn't know how.
Topic archived. No new replies allowed.