Declaring an object with a parameterized constructor inside another class C++ [duplicate]

  c++, class, constructor, pointers

I wish to have an object of one class contained inside a different class.

class A contained inside class B as in the simple example below.

The problem is that class A only has a parametrized constructor.

Is there another way to do declare the class A object in class B without having to use a pointer to class A ?

class A
{
    public:
        A(int var1, int var2);
    private:
        //...
};

class B
{
    public:
        B();
    private:
        A  a;      // Compiler error 
        A* a_ptr; // This will of course work fine. We can create a new A object with parameters any time using the a_ptr
};

Source: Windows Questions C++

LEAVE A COMMENT