Whenever we create an object from a class, it is created on the heap occupying more space as compared to a a struct variable which occupies its memory on stack. If i create a class of Person and a struct P, having same attributes, then it should justify what I just said. Please examine the following 2 fragments of code:
#include <iostream.h>
#include <conio.h>
#include <string>
using namespace std;
class Person{
int age;
string hair_color;
float height;
public:
Person::Person(int n)
{
age = n;
}
int Person::getAge()
{
return age;
}
};
struct P{
int age;
};
main()
{
Person person(45);
//Person *person = new Person(45);
P myPerson;
cout<<sizeof(person)<<endl;
cout<<sizeof(myPerson)<<endl;
//cout<<"Age: "<<person->getAge();
getch();
}
And when i write this code:
#include <iostream.h>
#include <conio.h>
#include <string>
using namespace std;
class Person{
int age;
string hair_color;
float height;
public:
Person::Person(int n)
{
age = n;
}
int Person::getAge()
{
return age;
}
};
struct P{
int age;
};
main()
{
// Person person(45);
Person *person = new Person(45);
P myPerson;
cout<<sizeof(person)<<endl;
cout<<sizeof(myPerson)<<endl;
getch();
}
Please correct me if I am wrong here about objects and refernces. I want to know from my code what occupies more space: Object or Struct?