Please help me to fix the errors.

Please help me to correct the logic and errors.

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>

using namespace std;

class Class1
{
    public:
        int val;
        int total;

        void print()
        {
            cout<<val<<endl;
        }

        void setValue(int n)
        {
            val=n;
        }

};

class Class10:public Class1
{
    public:
        Class10(int n)
        {
            val=n;
            total+=val;
        }
};

class Class11:public Class1
{
    public:
        Class11(int n)
        {
            val=n;
            total+=val;
        }
};

int main()
{
    Class1* ptr1 = new Class10(5);
    ptr1->print(); // should print 5
    Class11* ptr11 = new Class11(10);
    ptr11->print(); // should print 10
    ptr1 = ptr11;
    ptr11->print(); // should print 10;
    Class11 obj11;
    obj11.setValue(20);
    obj11.print(); // should print 20
    cout<<Class1::total<< endl; //should print 35 that is 5 + 10 + 20

    return 0;
}
So what makes you think there are logic problems or syntax errors?

Line 54 should be an error. Since total is not a static const member, it shouldn't exist without one of your class objects. Even if it is a static const member, you would have to assign a value to it first.

Even if you do that, your assumption //should print 35 that is 5 + 10 + 20 is wrong, since then you can't change total (which is now a const variable). Even assuming you could, the only place you do anything to the value of total is in your derived classes' constructors.

Also, the constructors for your derived classes do not set total equal to some value first. That means total is equal to some undefined value when you do total+=val;
Topic archived. No new replies allowed.