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