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

class B: public A
{
};

In class B i want to make m_a private. Does the following the correct way to do it

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

Won't this result in 2 copies of m_a ?

cspolton
  • 4,495
  • 4
  • 26
  • 34
KodeWarrior
  • 3,538
  • 3
  • 26
  • 40
  • The answer to this question here may also help: http://stackoverflow.com/questions/2804880/in-c-what-is-the-scope-resolution-order-of-precedence-for-shadowed-variab – Tony The Lion Sep 20 '12 at 10:46

3 Answers3

5

The correct way to adjust the access control of a member is with a using declaration:

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

Just writing int m_a; would indeed result in two copies of m_a, and a derived class would be able to access A's copy of m_a by writing A::m_a.

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
2

The m_a in class B shadows that of class A. It is a different data member, so class B actually has three ints: A::m_a, A::m_b and B::m_a. The way to get private access to m_a in B is to "use" A::m_a privately 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!
  }
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • If that's the case, we would be getting redeclaration error is that right ? But I don't seem to get. – KodeWarrior Sep 20 '12 at 10:44
  • Not at all. but it does isolate m_a to B-code to be the one declared in B. The one in A is hidden from that point on unless class-resolved (A::m_a or ::m_a) – WhozCraig Sep 20 '12 at 10:46
  • No, it isn't a re-declaration: `A::m_a` and `B::m_a` are separate members in each instance of `B`. The name lookup rules may be confusing, though. – Useless Sep 20 '12 at 10:46
  • @KodeWarrior if you want to see name hiding in action, declare a function ``void foo()`` in ``class A``, then an ``int foo`` in ``class B``. – juanchopanza Sep 20 '12 at 11:14
0

This code create three int storages in the class B.

The declaration of m_a creates a new variable - there is no redeclaration problem in c++ here as the declarations are in different scopes, more specifically A::m_a is not the same as B::m_a.

Elemental
  • 7,365
  • 2
  • 28
  • 33