-4

Suppose there is a 3 level inheritance.

Classes A<-B<-C.

Can methods of B class access members of C which is derived from it?

Assume suitable mode of inheritance.

niton
  • 8,771
  • 21
  • 32
  • 52

1 Answers1

5

A parent class cannot access data from a child class without "tricks", e.g.

class A
{
protected:
  int m_a;
};

class B : public A
{
protected:
  int m_b;
};

B can access m_a, A cannot access m_b. To get this behaviour you can use polymorphism and an accessor function

class A
{
protected:
  virtual int GetVar() { return m_a; }
private:
  int m_a;
}

class B : public A
{
protected:
  virtual int GetVar() { return m_b; }
private:
  int m_b;
}

Now A can access m_b through calling GetVar() e.g.

void A::DoSomething()
{
  // I want to do something to the variable, 
  int myVar = GetVar();
}

Now if the instance is type A then A::GetVar() is called, if the instance is type B then B::GetVar() will be called instead

MrShiny608
  • 106
  • 2