Simple inheritance question.

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
#include <iostream>

using namespace std;

class BaseClass{
public:
    BaseClass():nValue(0){}
    void inc(){
        nValue++;
    }

    void print(){
    cout << "\nnValue of BaseClass object = " << nValue << ".\n";
    }
protected:
    int nValue;

};

class SubClass:BaseClass{
public:
    SubClass(){
    nValue = 1;
    }

private:
    int nValue2;


};


int main()
{
    BaseClass x1;
    x1.inc();
    x1.print();

    SubClass x2;
    x2.inc();
    x2.print();

    return 0;
}


I've just finished learning the basics about inheritance and thought I'd have a little play around. The above program returns the errors:

"error: 'void BaseClass::inc()' is inaccessible"
"error: within this context"
"error: 'BaseClass' is not an accessible base of 'SubClass'".
(and the same for the print() function)

This confuses me since I thought the whole idea of inheritance is that the functions & data of a base class can be used in its subclasses as if it were contained in the subclass.

Any help would be appreciated.
Last edited on
BaseClass was inherited as private by default for class definitions.

class SubClass:BaseClass {

So its public members became private members of the derived class and are not acceptable outside the derived class definition.
To fix this: class SubClass: public BaseClass {
Oh dam of course! Thanks. :p
Topic archived. No new replies allowed.