Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Passing object to class constructor, how is it stored?

Consider the following example of a simple class implementation in C++.

foo.hpp

#include <vector>
class Foo {
private:
    std::vector<double> X;
public:
    Foo() = default;
    ~Foo() = default;
    Foo(std::vector<double>&);
};

foo.cpp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include "Foo.hpp"
Foo::Foo(std::vector<double>& X):
        X(X)
{}

In this case, the vector X is passed by reference to the constructor of the class Foo. I start having doubts, though, on whether the operation X(X) in the implementation makes a copy and pastes it "in" the member X of the class.

Which is it?

>Solution :

Yes, the data member X will be copy-initialized from the constructor parameter X.

If you declare the data member X as reference, then no copy operation happens. E.g.

class Foo {
private:
    std::vector<double>& X;
public:
    ~Foo() = default;
    Foo(std::vector<double>&);
};

Foo::Foo(std::vector<double>& X):
        X(X)
{}

Then

std::vector<double> v;
Foo f(v); // no copies; f.X refers to v
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading