Q:

C++ program printing random values

I was trying OOP with C++. I declared a class testOOP and created some private members in it. I added the value in the encapsulated array with add(int x) function. But when I tried to print it through printArray method it is outputting incorrect result.
Below is what I tried. Can somebody explain me why I am getting result different than 20 10 30 40?
#include <iostream>

using namespace std;

class testOOP
{
    private:
        int *a;
        int size;
        int last;

    public:
        testOOP();
        void add(int);
        void printArray();
};

testOOP::testOOP(void){

    size = 15;
    last = -1;
    int data[size];
    a = data;
    for(int i=0;i<size;i++){
        *(a+i)=0;
        //cout<<*(a+i);
        //cout<<"\n";
    }
}

void testOOP::printArray(){
    for(int i=0;i<=last;i++){
        cout<<*(a+i)<<" ";
    }
    cout<<endl;
}

void testOOP::add(int x){
    if(last+1 != size){
        last = last+1;
        *(a+last)=x;
    }
}

int main( )
{
    testOOP A;
    A.add(20);
    A.add(10);
    A.add(30);
    A.add(40);
    A.printArray();
    return 0;
}

And if possible how I can fix this issue?

A:

With the code in the constructor:
int data[size];
a = data;

data is a local array which will be destroyed when go out of the constructor. Then a will be dangled, dereference on it is UB. You could
1.new[] the array in the constructor (and delete[] it in the destructor). Such as:
testOOP::testOOP(void){

    size = 15;
    last = -1;
    a = new int[size];
    for(int i=0;i<size;i++){
        *(a+i)=0;
        //cout<<*(a+i);
        //cout<<"\n";
    }
}

2.use std::array or std::vector.

