Access to base class from derived class

I realize this is probably a very easy question for most. However, can anyone tell me how to modify this short piece of code so that the values printed to the screen are both the number 6? What I am trying to achieve here is "real-time" access to the base class for the wtfo class, in the example, the variable anint.

I'm assuming I will have to pass the address of the base class to the wtfo class to do this. Perhaps this is not a good use of base and derived classes?

Thank you very much in advance.


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

class base
{
public:
    base() : anint(3) { }
    virtual ~base() { }
    int get_base_anint() { return anint; }
    void set_base_anint (int i) { anint = i; }
private:
    int anint;
};

class wtfo : public base
{
public:
    wtfo () {}
    virtual ~wtfo() { }
    int get_wtfo_anint () { return get_base_anint(); }
};

int
main(int argc, char** argv)
{
    base* b = new base();
    wtfo* w = new wtfo();
    b->set_base_anint(6);
    cout << w->get_base_anint() << endl;
    cout << b->get_base_anint() << endl;

    return 0;
}
Last edited on
Simply add w->set_base_anint(6); immediately after line 29.

Remember that public inheritance indicates an is-a relationship: a wtfo is a base. In general, a publicly derived class (i.e., a subtype) should be usable anywhere a base-class is expected; this idea is called Liskov substitutability. But clearly you understood this, since you wrote w->get_base_anint() on line 31...

In order to make the is-a relationship efficient, as far as single inheritance is involved, the address of the base class is the address of the derived class.
You have created two objects. Changing the anint on one of the objects will not automatically change the anint for the other object.

Perhaps you intended b and w to point to the same object?

1
2
3
4
5
wtfo* w = new wtfo();
base* b = w;
b->set_base_anint(6);
cout << w->get_base_anint() << endl; // prints 6
cout << b->get_base_anint() << endl; // prints 6 
Last edited on
I want to thank you both (mbozzi and Peter87) for your answers; Peter87, you gave me what I needed there with that. It's nice to have folks provide help without condescension, snide comments or passive aggressive quips. Again, thanks to you both!
Topic archived. No new replies allowed.