user2991252
user2991252

Reputation: 788

Pointers and dereferenced pointers

I have this declaration in the header file

private:
MyIntegerClass *myArr;
MyIntegerClass myIntegerClass;
MyIntegerClass *ptr_myIntegerClass = &myIntegerClass;

MyIntegerClass is a class that have one data memeber that holds an integer. It has two member-functions - an accessor and a mutator.

And this is the cpp-file of the Array-class - the class that allocates memory for the array, and fills the array with values and lastly prints the array

Array::Array() {

    myArr = new MyIntegerClass[10];
    for (int i = 0; i < 10; i++) {
           ptr_myIntegerClass->setNumber(i);
           myArr[i] = *ptr_myIntegerClass;
    }
}

Array::~Array() { }

void Array::printArray() {
    for (int i = 0; i < 10; i++) {
        cout << myArr[i].getNumber() << endl;
}

I am new to C++ and I have thorough certain knowledge of C and through trial and error made this program that compiles and print these values without errors. But there's a couple things I do not understand:

For what I know - to put an * ahead of an pointer means that you dereference the pointer? right? So how could myArr that is a pointer store this dereferenced value? Or am I wrong about that myArr is a pointer? But why is it declared with a * in the header file?

Upvotes: 3

Views: 140

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The asterisk and the square brackets both decrease the level of dereference. In fact, myArr[i] is equivalent to *(myArr+i), and *ptr_myIntergerClass is equivalent to ptr_myIntergerClass[0]. Therefore, your assignment is equivalent to either

*(myArr+i) = *ptr_myIntergerClass;

or

myArr[i] = ptr_myIntergerClass[0];

which are both valid, because both their sides have the same type (i.e. MyIntergerClass) and the left side is assignable (i.e. an lvalue).

Upvotes: 5

Related Questions