C++ classes and inheritance

Why in void ClassB::count() the ++plus does not work? Can someone explain please. And how would be the best way to make it work?

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
#include <iostream>
#include <cstdlib>
using namespace std;

class ClassA
{
    public:
        ClassA(int);
        void print();
    private:
        int plus;
};
class ClassB: public ClassA
{
    public:
        ClassB(int,int);
        void print();
        void count();
    private:
        int minus;
        int plus;
};
ClassA::ClassA(int PLUS)
{
    plus=PLUS;      
}
void ClassA::print()
{
    cout << plus << endl;    
}
//////////////////////////////////////////////////////
ClassB::ClassB(int PLUS, int MINUS) : ClassA(PLUS)
{
    minus=MINUS;      
}
void ClassB::print()
{
    ClassA::print();
    cout << minus << endl;    
}
void ClassB::count()
{
    ++plus;
    --minus;
}
int main()
{
    ClassB b(5,5);
    b.print();  // i get on the screen 5 and 5 like it should be
    
    b.count(); // i do ++plus and --minus
    b.print(); // so i expect to get 6 and 4. but what i get is 5 and 4. the ++plus doesnt work :(
    
    system ("pause");
    return 0;
} 
In classB, you are overriding classA's "plus" member with its own "plus" member. Try getting rid of line 21, and that should fix your problem.
Does not work if i remove it i get ( 'int ClassA::plus' is private ) error
is there a way to fix it without removing it? tnx for your quick reply
Oh, didn't see that. Where you have "private", replace it with "protected". This means that inherited classes can see the variables for that class in the section, though the variables still aren't viewable outside of that. Try that.

EDIT:
Yeah, it works:
http://ideone.com/LzKOZO
Last edited on
Thank you for your help! changing to protected fixes it.
It works all fine but i need the line 21 to stay. Is there any other option? And why the plus value is not known in ClassB? it should get inherited ?
Topic archived. No new replies allowed.