Usman Kabir Usman Kabir - 1 year ago 90
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.

Answer Source

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) {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download