i trying oop c++. declared class testoop
, created private members in it. added value in encapsulated array add(int x)
function. when tried print through printarray
method outputting incorrect result.
below tried. can explain me why getting result different 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]; = 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 can fix issue?
with code in constructor:
int data[size]; = data;
data
local array destroyed when go out of constructor. a
dangled, dereference on ub. could
1.new[]
array in constructor (and delete[]
in destructor). such as:
testoop::testoop(void){ size = 15; last = -1; = 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
.
Comments
Post a Comment