1

I have this class in Python that I am trying to recreate in C++,

class Node:
    
    def __init__(self, data = None, next = None):
        self.data = data
        self.next= next

So far I have constructed this in C++, .h

#include<stdlib.h>
#include <iostream>

class Node {
    public:
        int value;
        Node* next;
        
        Node(int value, Node next) : value(0), next(NULL){
            std::cout << "inside .h" << "\n";
        };
};

and .cpp

Node::Node(int value, Node next) {
    this->value = value;
    this->next = &next;   
}

The code itself confuses me, it is usually best practice to avoid writing methods inside the .h but it wouldn't let me set the default values without {...}, i.e. I could not type Node(int value, Node next) : value(0), next(NULL); which I initially expected. It seems that I have defined two constructors aswell, which seems odd given the same parameters.

inside main it is not allowing me to instantiate an object as Node(5) etc...

Do we have a new way in C++ to mimic the Python class above?

2
  • Those aren't default values. Those are field initializers. You're completely ignoring the arguments. Commented Jun 30, 2021 at 5:28
  • I think you mean "how can I recreate default arguments in C++" Commented Jun 30, 2021 at 5:28

1 Answer 1

6

You do it the same way, by providing default arguments:

Node(int val = 0, Node* nxt = nullptr) : value(val), next(nxt) {}

This is both the default constructor, and the one that takes an int and a pointer to Node.


As a sidenote:

You may want to have the following form instead, adds flexibility:

Node(Node* nxt = nullptr, int val = 0) : next(nxt), value(val) {}

This way you can create (connect) a Node with default value:

Node n(&next_node); // a Node instance with default value 0
Sign up to request clarification or add additional context in comments.

3 Comments

I am having a look at the link you provided but I can't seem to find where they talk about default arguments using the example(type x, type y): x(...), y(...)
@Joe changed the link to a more appropriate one. Check the first paragraph.
oh, I see this is what the first comment meant, those are field initializers...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.