Problem with inheritance

I don't understand what's going on here, it seems like there is an easy solution but I can't figure it out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef A_H
#define	A_H

class A
{
public:
    A();
    void set_foo(char new_foo);
    char get_foo() const;
private:
    char foo;
};

#endif 
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "A.h"

A::A() : foo('f') {}

void A::set_foo(char new_foo)
{
    foo = new_foo;
}

char A::get_foo() const
{
    return foo;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef B_H
#define	B_H
#include "A.h"

class B : public A
{
public:
    B();
    void set_bar(int new_bar);
    int get_bar() const;
    void print() const;
private:
    char foo;
    int bar;
};

#endif 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "B.h"
#include <iostream>

using namespace std;

B::B() : foo('f'), bar(1) {}

void B::set_bar(int new_bar)
{
    bar = new_bar;
}

int B::get_bar() const
{
    return bar;
}

void B::print() const
{
    cout << foo << bar;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "B.h"

using namespace std;

int main()
{
    B b;
    b.set_foo('g');
    b.set_bar(2);
    b.print();

    return 0;
}


Output:
f2
If you're using A's set_foo() then you're setting A's char foo, not B's.
B's char foo you're setting in B::B() : foo('f'), bar(1) {}, defaulting it to f.
If you make foo portected or public in A i think it will work.
If you make foo portected or public in A i think it will work.


That's the first step.
Second step: remove B's char foo.
Third step: change your fancy
B::B() : foo('f'), bar(1) {}
into
1
2
3
4
5
B::B()
{
    foo = 'f';
    bar = 1;
}
^ Secont step makes sense.

First step is pointless. You provide accessors in A. (but yeah, you could avoid those accessors by making the variable public)
Third step, ¿what's the difference? and you should let 'A' handle 'A' members (its constructor already take care of that)
Topic archived. No new replies allowed.