Medvednic
Medvednic

Reputation: 692

How to return nested class pointer from method?

I have two classes: Database and Node as a nested class, is it possible to have a method of Node that will return a Node*?

I tried to set the method nextNode return type as Node* but I get a compilation error: 'Node' does not name a type

Databse.h

class Database
{
    public:
        Database();
        Database& operator+=(const Client&);
        ~Database();
    private:
        class Node //node as nested class
        {
            public:
            Node(); //ctor
            void setHead(Client*&); //add head node
            Node* nextNode(Node*&); //return new node from the end of he list
            private:
            Client* data; //holds pointer to Client object
            Node* next; //holds pointer to next node in list
        };

        Node *head; //holds the head node
};

nextNode method declaration in Databse.cpp:

Node* Database::Node::nextNode(Node*& start)
{
....
....
    return current->next;
}

Thanks.

Upvotes: 2

Views: 2887

Answers (2)

Quentin
Quentin

Reputation: 63154

Additionally to juanchopanza's answer, C++11's trailing return type allows you to declare it in-scope :

auto Database::Node::nextNode(Node*& start) -> Node* {
    // ...
}

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227498

Node is nested in Database, so you need the scope for the return type:

DataBase::Node* Database::Node::nextNode(Node*& start)
^^^^^^^^^^

The parameter is already in scope, so you may leave it as is.

Upvotes: 7

Related Questions