-6

This is my class

#include <vector>

class MyClass
{
    public:
        void print(); // prints X to console

    private:
        std::vector<int> X (4, 100);

};

When I call the print() method I want X to be passed by constant reference to print(). How can I do that? Currently is looks like as X is passed by value.

Gilfoyle
  • 3,282
  • 3
  • 47
  • 83
  • What do you mean? You currently don't pass anything to print(). You don't need to pass X to be able to use it inside of print() either. – Eric Jun 15 '20 at 10:38
  • 2
    If you just want to be sure that `X` won't be modified in `print()`, make it a _constant member function_. – Daniel Langr Jun 15 '20 at 10:42
  • @Bathsheba Ok, I understand that. But how do I tell the program that `print()` does not modify the content of `X`? – Gilfoyle Jun 15 '20 at 10:42
  • `const std::vector X (4, 100);` and/or `void print() const;` – Thomas Sablik Jun 15 '20 at 10:43
  • @ThomasSablik What do I do if I have an additional function that changes the content of `X`? – Gilfoyle Jun 15 '20 at 10:45
  • 2
    Then only `void print() const;` – Thomas Sablik Jun 15 '20 at 10:46
  • 2
    Does this answer your question? [Meaning of 'const' last in a function declaration of a class?](https://stackoverflow.com/questions/751681/meaning-of-const-last-in-a-function-declaration-of-a-class) – Daniel Langr Jun 15 '20 at 10:46
  • You could also write a member function or free function: void actual_print(const std::vector& x) that you call from print() – Sebastian Jun 15 '20 at 13:45

1 Answers1

2

Ok, maybe this will help you to start thinking in c++, even if you did not make clear explanation what you need, if I may guess, what you probably think of is that you want to be able to call print() member function on const instances of MyClass, or rvalue has been bound to const lvalue reference, so you need to mark print as const member function of type MyClass.

class MyClass
{
    public:
        void print() const; // prints X to console

    private:
        std::vector<int> X (4, 100);

};
Boki
  • 637
  • 3
  • 12