I'm moving from java to c++ and and as I learn how things are done in C++, I sometimes get confused. I read online that if an object is created inside of a function it only exist inside the function unless it's declared using new. So I wrote the following code to test it:
#include <iostream>
using namespace std;
class Student{
private:
int ID;
int score;
public:
void setID(int num);
int getID();
void setScore(int num);
int getScore();
};
void Student::setID(int num)
{
ID = num;
}
int Student::getID()
{
return ID;
}
void Student::setScore(int num)
{
score = num;
}
int Student::getScore()
{
return score;
}
class Creator
{
public:
static int nextID;
Student getObject();
};
int Creator::nextID = 0;
Student Creator::getObject()
{
Creator::nextID++;
Student temp;
temp.setID(Creator::nextID);
return temp;
}
int main()
{
Creator maker;
Student pupil[4];
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
pupil[i] = maker.getObject();
}
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
cout<< "Sudent ID: "<<pupil[i].getID()<<endl;
}
int mark = 70;
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
pupil[i].setScore(mark);
mark += 10;
}
for(std::size_t i = 0; i < (sizeof(pupil)/sizeof(pupil[0])); i++)
{
cout<< "Sudent ID: "<<pupil[i].getID()<<" has score of: "<<pupil[i].getScore()<<endl;
}
return 0;
}
The program works as expected and that is what is confusing me. According to what I read the object created inside of Student Creator::getObject()
should not exist outside of it. It's destroyed as the function returns. Yet, I'm returning the object that was created inside of Student Creator::getObject()
and storing it in the pupil array, outside of Student Creator::getObject()
.
Since it works, does it mean that the object was created on the heap? From what I read, if the object is created inside of a function and the new keyword wasn't used the object is created in the stack and destroyed as the function exits.