1

Here are 2 classes

class B
{
private:
    int x;
public:
    friend std::istream& operator>>(std::istream& in, B& obj)
    {
        in >> obj.x;
        return in;
    }
};

class D: public B
{
private:
    int y;
public:
    friend std::istream& operator>>(std::istream& in, D& obj)
    {
        //?
    }
};

Is there any way that I can overload the >> operator in class D so it will be able to access the element x in B?

1
  • To be more specific, make x protected ;) Commented Apr 2, 2013 at 20:44

3 Answers 3

1

Based on what you appear to be trying to do, you could also do this:

class B
{
private:
    int x;
public:
    friend std::istream& operator>>(std::istream& in, B& obj)
    {
        in >> obj.x;
        return in;
    }
};

class D: public B
{
private:
    int y;
public:
    friend std::istream& operator>>(std::istream& in, D& obj)
    {
        B* cast = static_cast<B*>(&D); //create pointer to base class
        in >> *B; //this calls the operator>> function of the base class
    }
};

Although there are probably other reasons to make x protected instead of private anyway.

Sign up to request clarification or add additional context in comments.

Comments

1

Is there any way that I coverload the >> operator in class D so he will be able to access the element x in B?

Don't make x private.

By making it private, you're explicitly saying that access to it is restricted to class B and its friends. And from your question, it seems that you don't want that.

If it were protected instead, you could access it as obj.x.

1 Comment

I'm afraid this wouldn't work, because operator >> here is a friend of D, not a member function
0

x needs to be protected. Otherwise it is not accessible directly from D.

class B
{
protected:
    int x;

Then you can do

class D: public B
{
private:
    int y;
public:
    friend std::istream& operator>>(std::istream& in, D& obj)
    {
        in >> obj.x;
        return in;
    }
};

1 Comment

x is inherited by D in the sense that D has an x data member. It is just not accessible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.