inheritance problem

this program should be calculating the total and average from the given values by the user but it does not...what's wrong with this program???

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <string>
using namespace std;
class stuPersonal
{
      protected:
                string name, rollno, sex;
                short age;
      public:
             stuPersonal(string n, string r, string s, short a)
             { name = n; rollno = r;
               sex = s; age = a; }
};
class stuMarks
{
      protected:
                double mark1, mark2, mark3, mark4;
      public:
             stuMarks() {}
             stuMarks(double m1, double m2, double m3, double m4)
             { mark1 = m1; mark2 = m2; mark3 = m3; mark4 = m4; }
};
class stuSports
{
      protected:
                double score;
};
class stuResult : public stuMarks, public stuSports
{
      protected:
                double total, avg;
                char grade;
      public:
             void totalnavg()
             { cout << "Total = " << mark1 + mark2 + mark3 + mark4 << endl;
               cout << "Average = " << (mark1 + mark2 + mark3 + mark4)/4 << endl; }
};
int main()
{
    string n, r, s; short a;
    double m1, m2, m3, m4;
    cout << "\n\tHELLO, THERE!\n"
         << "\nPlease fill in the following\n"
         << "   Name  : "; cin  >> n;
    cout << "Roll no. : "; cin  >> r;
    cout << "    Age  : "; cin  >> a;
    cout << "    Sex  : "; cin  >> s;
    stuPersonal personalobj(n,r,s,a);
    cout << endl << n << ", Please enter your marks:\n"
         << "Marks1 : "; cin  >> m1;
    cout << "Marks2 : "; cin  >> m2;
    cout << "Marks3 : "; cin  >> m3;
    cout << "Marks4 : "; cin  >> m4;
    stuMarks marksobj(m1,m2,m3,m4);
    stuResult resultobj;
    resultobj.totalnavg();
    system("pause");
}
Last edited on
Line 55: You instantiate resultobj, but you don't initialize it. What do you think mark1-4 contain?

This should be:
 
    stuResult resultobj (marksobj);


This implies that stuResult has a constructor that accepts a stuMarks object.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
i added in class stuResult this:

stuResult(stuMarks) {}

and i changed line 55 to be:
stuResult resultobj (marksobj);

but still it doesn't work...it keeps printing garbage values as results.

Last edited on
Your added constructor does nothing. You still have not initialized the members of the inherited class.

Proper constructor:
1
2
    stuResults (const StuMarks & marks) : stuMarks (marks)     
    {}

Note the underlined portion. This calls the constructor of the inherited class.
it worked...thanks a lot for your help.
Topic archived. No new replies allowed.