Hey, I am trying to do a simple program using class. I just learned how to write in class however I do not know how to add variables. This is what I have so far:
#include <iostream>
using namespace std;
class StudentScore{
private:
int quiz1, quiz2, midterm, final;
double total_quiz, final_mid, total_final, grade;
public:
double get_quizes();
double get_mid();
double get_final();
};
int main ()
{
StudentScore student1;
student1.get_quizes();
student1.get_mid();
student1.get_final();
return 0;
}
double StudentScore::get_quizes()
{
cout<<"Input first quiz:"<<endl;
cin>>quiz1;
cout<<"Input second quiz:"<<endl;
cin>>quiz2;
total_quiz=(quiz1+quiz2)*.25;
return total_quiz;
}
That makes sense but I can take all of the variables and add them up and assign them to a new variable no? Whats the class equivalent to:
x=9
y=5
z=x+y
I need to add up all the scores for student1 to get the variable grade. Is it as simple as:
grade=total_quiz+final_mid+total_final;
cout<<grade<<endl;
Or is there more to it? Do I have to use the '.' in-between? I don't know what to do, I am trying to practice, but my teacher did not get to finish the chapter on class.
Since grade,total_quiz,final_mid,total_final are all private variables;
you will not be able to access them directly from main().
However, you will be able to access them directly from any member function of the class StudentScore.
So, you can write a new function similar to get_quizzes(), and calculate grade and display it.
Willbe something as follows:
class StudentScore{
private:
int quiz1, quiz2, midterm, final;
double total_quiz, final_mid, total_final, grade;
public:
double get_quizes();
double get_mid();
double get_final();
void calculate_grade(); //It is not going to return anything, so void
};
And then call this from main().
int main ()
{
StudentScore student1;
student1.get_quizes();
student1.get_mid();
student1.get_final();
student1.calculate_grade();
My_class.x = 9; Where My_class is an instantiation of StudentScore. As kameswarib has already said, the members are private, which means they cannot be touched from outside of the class.
What I would do personally, is add a member function that computes the overall grade. After computing the grade, it would return it. For instance:
Note that the const following the function parameter list means the function is constant. This prevents the function from modifying the members of the class (read-only).