0

I'm trying to have a member function of classA set valuea to what ever valueb of classB is. I don't really have a full grasp of inheritance so forgive me if it's a simple or stupid mistake. Also Would it be easier to make the convert function a friend of both classes instead?

class B
{
    protected:
    int valueb;

public:
        B() { }
        B(int x) {valueb=x;}
};

class A: public B
{
    int valuea;
public:
    A():B() {}
    A(int x):B(x) {valuea=x;}
    void convert(B x)
    {
        valuea = x.valueb;
    }
    int getValue() {return valuea;}

};


int main( )
{
    A a(1);
    B b(2);

    a.convert(b);

    cout << a.getValue() << endl;
}
Tony606
  • 23
  • 2
  • 1
    `class A` cannot access `valueb` from the parameter since it's protected. But `A` already is a `B`, so `valuea = B::valueb;` works. I don't know though if this matches your intend. See a working sample: http://ideone.com/NiQQAF – πάντα ῥεῖ Oct 22 '15 at 16:20

1 Answers1

0

Your question would be more readily answered if you had stated the problem you are trying to solve with this design, but I'll throw in a few cents.

I'm trying to have a member function of class A set valuea to what ever valueb of class B is.

This doesn't make much sense as A inherits from B. An A is a B. It would make more sense if an A had B as a part, i.e.

class A{
    B partOfA;

Your name convert suggests that you might want to convert an object of type B to an object of type A, this is also quite odd but you can do it by having a constructor

A(const B& b):B(b){}

So instead of doing a "conversion" you create a new object

B b;
A a(b);

If your only goal is to access x.valueb from B you need a public accessor member in B. See for instance Accessing protected members in a derived class

Community
  • 1
  • 1
Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
  • Hey thanks, This was just a simple lab question for a class I'm taking. I was just over thinking it trying to use the stuff we were going over. I didn't even think of just adding an accessor function but that is obviously the way to go. sorry for the confusion. – Tony606 Oct 23 '15 at 02:29