Defining a Nested Class From Header File

1.4k Views Asked by At

Still fairly new with C++ and trying to kick it up a notch here. I would like to build a Heap class, with a nested Node class, and add a heap sort aspect to the Heap class. I have done something similar with Java, but I am getting stuck trying to define the nested class in the .cpp file.

#pragma once
#ifndef HEAP_H
#define HEAP_H

template <class T>
class Heap 
{

public:

    class Node
    {
    public:
        Node(T);
        T data;

    private:
        Node *parent;
        Node *left_child;
        Node *right_child;
        boolean is_root;
    };


    Heap(T*, int);
    sort_it();


private:
    T *unsorted_list
    Node root;
    void build_heap();
    void add_node(Node);
    void swap_root();
    void trickle_down();
    void heap_sort();
};


#endif

Now when I go to define my nested class in the .cpp file I cannot simply...

#include "stdafx.h"
#include "Heap.h"
#include <iostream>

//Defining Heap Constructor
Heap::Heap(T* incoming_array, int _size)
    {
         unsorted_list = incoming_array;
         size = _size;
    }

//Defining Node Constructor
Heap::Node(T _data)
    {
        data = _data;
        left_child = right_child = parent = Null;
        is_root = false;
    }

I am not sure if my problem is how I am incorporating the template, or if my syntax for defining the inner class is wrong. Both Generic Programming and Nested Classes are unfamiliar to me in C++

1

There are 1 best solutions below

0
On

If you use any generic type in nested class you have to specify the template.

template<class T>
class Node

To define the template class constructor outside the class,

template<typename T>
Node<T>::Node(T _data)

Declare the member as follows,

Node<T> root