1

I'm not quite sure what the difference between passing *d and d2 to the constructor is:

#include <iostream>

using namespace std;

class Data
{

public:
    int number;
};

class Node {

public:

    Data data;  

    Node() {};

    Node(Data d) : data(d) {};

};

int main()
{
    
    Data* d = new Data();
    Node* n = new Node(*d);
    
    Data d2;
    Node* n2 = new Node(d2);


    return 0;
} 

I can pass *d and d2, but in both scenarios, the data member "data" in the class "Node" is still an object by itself, is that correct? Or is there even a difference between passing an object and a dynamic object?

4
  • 1
    There are three Data objects here: data member in the class, d constructor parameter, and either d or d2. The former two don't care about the third. Commented Dec 18, 2021 at 22:01
  • 2
    Right. Since this is C++ and not C#, all of those 4 objects are separate objects, and when you assign one to the other you are copying the data from one object to another. (You can print out the address of any object with printf if you want to check this.) Commented Dec 18, 2021 at 22:04
  • @David Grayson thanks, that answers my question :) Commented Dec 18, 2021 at 22:05
  • 1
    Actually, let's see, there are 4 long-lived data objects, and from the perspective of the main function they are named: *d, d2, n->data, and n2->data. There are also 2 temporary data objects that are created when you call the Node constructor Node(Data d), since calling that involves creating a Data object on the stack named d and you call the constructor twice. So there are 6 Data objects in sight and several copy (or move) operations are performed to pass data between them. Commented Dec 18, 2021 at 22:09

2 Answers 2

1

From Node's perspective, the constructor receives a Data object. It doesn't care if this object is dynamically allocated using new or not.

Sign up to request clarification or add additional context in comments.

Comments

0

from node perspective, the constructor of node need an object of type data ,so it only care about data object type, it don't care about its place in memory (static memory or dynamic memory) *d and d2 represent data objects so your code is correct.

Comments

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.