Member Class with Constructor Parameters

Hey everyone.

I have a problem and I was wondering if someone could help.

Suppose I have a class A, with the following definition:
1
2
3
4
5
public class A
{
  A(int x, int y);
  ~A();
};


Then suppose, I have a class B, that needs class A as one of it's members:

1
2
3
4
5
6
7
8
public class B
{
  B();
  ~B();

private:
  A;
};


How would I then supply both the ints as arguments to the constructor of A? I have been getting around this, by declaring A to be on the heap, and then when I create a new instance of A with the new operator in B's constructor I can pass in the arguments then, but does anyone know how to do this with A being on the stack?

Thanks,
Matt

1
2
3
4
5
6
7
8
9
class A {
   A(int x, int y);
   ~A();
};

class B : public A {
   B(int x, int y) : A(x, y);
   ~B();
};


Do you mean like that?
If A is used for a member of B try something like this:
1
2
3
4
5
6
7
8
class B
{
    B() : a ( 1, 2 ) {}
    ~B();

    private:
        A a;
};
Last edited on
Bazzy if Class members are private by defualt, what does that make lines 3 and 4 of your example?
They make possible to construct/destruct B only within the class itself or its friends.
Usually those should be public but this is what the OP had

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class B
{
    B()  {}
    ~B() {};
    friend int main();
};

int notmain()
{
    B b; //   :-(
    return 0;
}

int main()
{
    B b; //   :-)
    return notmain();
}
Last edited on
Topic archived. No new replies allowed.