derived classes

Jun 26, 2019 at 5:18pm
From article :
protected members are accessible from other members of the same class (or from their "friends"), but also from members of their derived classes.

It means that protected members are the same as private members, but it can also access derived classes right??

So, what is the meaning of "derived classes"???
If its possible can you give me an example to make it easier to understand..

Thanks..
Jun 26, 2019 at 5:35pm
A derived class = subclass = child class, in OOP.
See also: https://www.geeksforgeeks.org/inheritance-in-c/

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
// Example program
#include <iostream>
#include <string>

// BASE (PARENT) CLASS
class smorgas { 
  public:
    int public_var = 1;
  protected:
    int protected_var = 2;
  private:
    int private_var = 3;
};

// DERIVED (CHILD) CLASS
class smorgasbord : public smorgas {
    void bord()
    {
        int s = public_var; // compiles
        int r = protected_var; // compiles
        
        int q = private_var; // won't compile! (can't access private var from derived class)
    }
};

int main()
{
    smorgas smorg;
    
    int s = smorg.public_var; // compiles
    
    int r = smorg.protected_var; // won't compile! (can't access protected var from outside class)
    int q = smorg.private_bar; // won't compile! (can't access private var from outside class)
}

Comment out the "won't compile" lines to have it compile.
Last edited on Jun 26, 2019 at 5:44pm
Topic archived. No new replies allowed.