Usman Kabir Usman Kabir - 4 months ago 14
C++ Question

How to create objects inside another class?

I have this code.

#include "Stack.h"

template <class dataType>
class Queue2{

Queue2(int size);

bool push(int data);
bool pop(int &data);

bool isEmpty();
bool isFull();

bool top(int &data);


template <class dataType>
Queue2<dataType>::Queue2(int size = 10) : Stack <dataType> obj1(size), Stack <dataType> obj2(size) {//here i am facing an error. how can i fix it


I have a templete class Stack with constructor like this.

Stack(int size=10);

Now I want to create two objects of Stack class in Queue2 class.


If you give your Queue2 class two private Stack members, you can initialize them in the constructor initialization, and access them individually:

class Queue2{
    Stack<dataType> left,right;
    Queue2(int size);
    /* ... */

You then define the constructor as:

template<typename dataType>
Queue2<dataType>::Queue2(int size = 10)
  : left(size), right(size) {}