what am i seeing : size of class ?
Apr 4, 2009 at 10:46pm UTC
hey,
could someone explain to me what it is that i'm seeing in the output. the 'this' pointer is 8 bytes apart between the 2 instances...:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <iomanip>
using namespace std;
class student{
private :
int hours;
float gpa;
public :
student(){
hours = 0;
gpa = 0.0;
cout << "in constructor 0 : " << endl;
cout << "hours = : " << hours << endl;
cout << "gpa = : " << gpa << endl;
}
student(int h,float g){
hours = h;
gpa = g;
cout << "in constructor 1 : " << endl;
cout << "hours = : " << hours << endl;
cout << "gpa = : " << gpa << endl;
}
~student(){
cout << "destroying : " << this << endl;
}
void addcourse(int coursehours,float grade){
float weightedgpa;
weightedgpa = hours * gpa;
hours += coursehours;
weightedgpa+= grade * coursehours;
gpa = weightedgpa / hours;
}
void printgpa(){
cout.setf(ios::fixed|ios::showpoint);
cout << "Hours = : " << hours << endl;
cout << "GPA = : " << setprecision(2) << gpa << endl;
}
};
#endif
output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
in constructor 0 :
hours = : 0
gpa = : 0
in constructor 1 :
hours = : 4
gpa = : 4
Enter # of hours this term : 16
Enter gpa earned : 4.0
Hours = : 16
GPA = : 4.00
Hours = : 4
GPA = : 4.00
destroying : 2ff229b8
destroying : 2ff229b0//huh?
i figured you don't need to see main() for this.i just don't want to make another bad assumption. thanks.
Last edited on Apr 4, 2009 at 10:52pm UTC
Apr 5, 2009 at 12:24am UTC
Because this is a pointer to the current object. Since you are creating two objects, they are not the same, and thus they have different memory addresses.
Apr 5, 2009 at 10:58am UTC
i understand that. my question is the difference in size between the instances. is this indicative of the size of the object(s)?
Apr 5, 2009 at 7:30pm UTC
I believe it is because the compilier is probably allocated them in 8 bytes increments...sort of like:
[DDDDD000][DDDDD000]
^Data ^nothing
Apr 5, 2009 at 9:17pm UTC
Well, the size of the data members of the class happens to be 8 bytes (on a 32-bit system), but you cannot make the assumption that consecutive new's of an object will yield pointers that are sizeof( classtype ) bytes apart.
Topic archived. No new replies allowed.