0

I am new in c++ and I am trying to understand the following c++ code:

Header file: arr.h

#include <iostream>

using namespace std;

#ifndef ARR_H
#define ARR_H

class arr {
private:
    int n;
    int *ar;
public:
    arr();
    arr(int nn, const int *a);

    ~arr();

    const int *Get_ar() const;
};

#endif

Cpp-file: arr.cpp

#include <iostream>
#include "arr.h"

using namespace std;

arr::arr() {
    n = 2;
    ar = new int[2];
    ar[0] = 1;
    ar[1] = 2;
}

arr::arr(int nn, const int *a) {
    n = nn;
    ar = new int[n];
    for (int i = 0; i < n; i++) {
        ar[i] = a[i];
    }
}

const int *arr::Get_ar() const {
    return ar;
}

arr::~arr() {
    delete [] ar;
}

Main file: main.cpp

#include <iostream>
#include "arr.h"

using namespace std;

int main()
{
    int n = 3;
    int *a = new int[3];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    int *get_a = new int[3];

    arr A(n,a);
    get_a = A.Get_ar();

    return 0;
}

When compiling I get the error: invalid conversion from 'const int*' to 'int*'. When I replace int *get_a in the main.cpp with const int *get_a it compiles fine. On the other hand if I delete the const from const int *Get_ar() const in the header file arr.h and in the cpp file arr.cpp it compiles without errors.

I do not understand, why I obtain compiler errors when I leave the code unchanged. Especially, I do not understand what exactly const int *Get_ar() const is returning.

For an explanation i would be very thankful.

Best, Phil

  • also a good read: https://stackoverflow.com/questions/38026665/c-conversion-from-const-int-to-int-working-with-unexpected-results – NathanOliver Jun 08 '21 at 14:29
  • Add a `int *Get_ar() { return ar; }` method to your class definition so it works with `this` being either const or non-const – m88 Jun 08 '21 at 14:30
  • `const int *Get_ar() const` defines a member function of class `arr` named `Get_ar` that does not modify the externally observable state of the `arr` object (the `const` at the end), and that returns a pointer to `const int`s - an array of integers whose value may not be changed. – JohnFilleau Jun 08 '21 at 14:30

0 Answers0