user3704771
user3704771

Reputation: 7

C++ new instance of nested class

Here is my code

template <typename T>
struct Item
{
    T* Product;
    Item *next;

    Item(T*);
};

template <typename T>
Item<T>::Item(T *prod)
{
    this->Product = prod;
    this->next = nullptr;
}

template <typename T>
class Catalog
{
private:
    Item<T> *first;
    Item<T> *last;
    unsigned int count;
public:
    struct Item;  //i need Item as nested structure

    void Add(T*);
};

template <typename T>
void Catalog<T>::Add(T *ptr)
{
    //only for simplification, algorithm I already have

    this->first = new Item<T>(ptr);
    //or
    this->last = new Item<T>(ptr);

}

I do not know how add new Item to my class Catalog. If Item is not nested struct, I can use simply new Item<T>(ptr)

Is any way how to do this?? It is my project to school and I need Item as nested struct.

Thank you, sorry about my English.

Upvotes: 0

Views: 144

Answers (2)

clcto
clcto

Reputation: 9648

You must put the definition inside the definition of the class:

template <typename T>
class Catalog
{
public:

    struct Item
    {
       T* Product;
       Item *next;

       Item(T*);
    };

    void Add(T*);

private:
    Item *first;
    Item *last;
    unsigned int count;
};

Note that now the struct's type is Catalog<T>::Item, so elsewhere you will have to use that instead of just Item<T>:

template <typename T>
Catalog<T>::Item::Item(T *prod)
{
    this->Product = prod;
    this->next = nullptr;
}

Upvotes: 0

James Kanze
James Kanze

Reputation: 153899

The problem is that you're declaring two different Item. The first is a non-nested template struct, which you (probably) don't want to use, and the second is an incomplete nessted struct. The second is the one you probably want to use, but it is incomplete, so you cannot create an instance of it. What you should do is put the entire definition of the Item in the class Catalog, instead of just the forward definition. (And don't define it there as a template: the type you want is Catalog<T>::Item, and not Catalog<T>:Item<U>.) Then, of course, inside the class template, it is new Item (and not new Item<T>); outside the class, it is new Catalog<T>::Item.

Upvotes: 1

Related Questions