<aside> 💡 Formal Definition A ****class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behaviour (member functions or methods).
</aside>
“Structs with functions!”
public
public
, private
and protected
export struct student{
int assn, mt, final; //fields of the receiver object
float grade();
};
float student::grade(){ //a member function (or method)
// :: called the scope resolution operator
return assn * 0.4 + mt * 0.2 + final * 0.4;
}
//formally methods take a hidden extra parameter called (this)
//-ptr to the reciever obbject
Student s {60, 70, 80}
// Student => Class
// s => object
When we see C::f
, it means f is the context of class C (the ::
is called the scope resolution operator (C is either a namespace or class)
Q: what’s the difference between a method and a function?
Ans: Methods take a hidden extra parameter called this
, which is a pointer to the receiver object
The following works
Student s{60, 70, 80}
But there is a much better way. We can use a constructor
<aside> 💡 Constructor is a method that initializes an object
</aside>
Here’s an implementation of it
struct Student {
int assignment, midterm, final;
float grade();
Student (int assignment, int midterm, int final);
};
Student::Student(int assignment = 0, int midterm = 0, int final = 0) {
this->assignment = assignment;
this->midterm = midterm;
this->final = final;
}
int main() {
Student s{60, 70, 80};
Student s = Student{60, 70, 80} // Alternative syntax (not-sementically identical??)
Student s2{70, 80} // 70, 80, 0
Student s3; // 0, 0, 0 (still calling the constructor!
}