Create one of the inherited protected members

class A
{
protected:
    int m_a;
    int m_b;
};

class B: public A
{
};

In class B, I want to make it m_aprivate. Is this being done right?

class B:public A
{    
private:
    int m_a;
};

Will this be the result in 2 copies m_a?

+5
source share
3 answers

m_ain the class B shade , << 22>. This is another data item, so class B actually has three ints: A::m_a, A::m_band B::m_a. The way to get private access to m_ain Bis to "use" A::m_aprivately in class B:

class A {
  int m_a;
};

class B:  public A {    
    using A::m_a;
};

class C : public B {
  void foo() { 
    m_a++; // ERROR!
  }
};
+2
source

The correct way to configure an access control is to declare using:

class B: public A {    
private:
    using A::m_a;
}

int m_a; m_a, A m_a, A::m_a.

+5

This code creates three storage classes in class B.

The m_a declaration creates a new variable - there is no problem with re-release in C ++, since the declarations are in different areas, namely A :: m_a is not the same as B :: m_a.

0
source

All Articles