Inheriting private members in C++
Asked Answered
S

8

23

suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private data members

Shuler answered 20/4, 2010 at 15:34 Comment(4)
A derived class does inherit private data members.Anstus
What is even more confusing is that you can override private virtual functions of the base-class.Boschvark
@Space_C0wb0y: That's not confusing at all. It's called the Template Method Pattern (which unfortunately has nothing to do with C++ templates)Shonda
And always think a second time when you add getters and setters for attributes: Sometimes they're perfectly fine but other times the work should be done through another, more descriptive, interface.Infarct
C
39

A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.

Communitarian answered 20/4, 2010 at 15:36 Comment(5)
@user265260: Probably, but why? That strikes me as a problem just waiting to happen. Members are private for a reason, and if you can play with their values you can mess up an object. Moreover, if the layout changes (and it can change between different compiles; an object with a size_t member is likely to have a different layout with 32-bit and 64-bit compiles), you're stomping on entirely different data.Albumenize
@user265260: That might work on your platform, but it is never required to work. Ever.Shonda
just to poke and hack around, i was just wondering how this is implementedShuler
Yes, you could manipulate the private data in a hackish, non-portable way using this and offsetting accordingly.Thrilling
@user265260: For learning what happens "under the hood", the best way would be to fire up your debugger and look at the addresses of the object and its data members. You could also pull up the debugger's "memory" view and see where the data goes in memory. Keep in mind that the behavior you'll see is platform/compiler specific.Thrilling
Y
11

It depends on the inheritance type. If you inherit privately, then the derived class does NOT have access to the Base's private members.

Access                      public     protected    private
-----------------------------------------------------------
members of the same class      yes           yes        yes
members of derived classes     yes           yes         no
not members                    yes            no         no
Yet answered 20/4, 2010 at 15:48 Comment(2)
I think this answer can be misleading or at least inaccurate. @Yet please try to make it more clear.Forcible
This does not answer the question asked.Aranyaka
M
5

They are included, but not inherited. What this means is:

  • Any inheriting type (: public SomeClass, : protected SomeClass or even : SomeClass, equivalent to : private SomeClass) will not make them accessible from child class methods, or outside (this->a and someobject.a respectively);
  • They will still be there - take space in memory allocated for child class instance;
  • Inherited methods will be able to access that private field.

So, basically protected is not visible outside while visible inside and from derived classes (if : private Parent wasn't used), while private is not visible from neither derived classes nor outside of the parent class; it's only visible for parent class' methods, even if they are inherited (but not overrided).

Mitsue answered 13/7, 2018 at 19:45 Comment(0)
S
3

Because the getters and setters are public -- they're callable by anyone, not just derived classes.

Shonda answered 20/4, 2010 at 15:35 Comment(5)
my doubt is how come you can manipulate the values of the private data members since clearly you cannot inherit themShuler
and those getters and setters are members of the base class, so they have access to the private data.Ekg
@user235230: "clearly you cannot inherit them" This is WRONG.Telson
Adam wants to keep the keys to his car private, so only he can use them. Even his kids don't have access. However, if he provides a public get method for his car keys, he's giving the whole town permission to drop by and take his car out for a spin. Of course that includes his children.Kissee
thank you @Kissee this is the thing i needed to convince myselfLw
V
2

you can access to them by set access to setters and getters public and acces to them like that

*.h


class Mamifere
{
private:
    int a;
public:
    Mamifere();
    virtual ~Mamifere();
    int getA();
    // ~Mamifere(); //le delete dans le exp02() affiche seulement mamifere mort :( destructeur de la class mere 
    void manger() ;
    virtual void avancer() const;
};


class Deufin:public Mamifere{
public:
    Deufin();
    void manger() const;
    void avancer() const;
    ~Deufin();
};




*.cpp

Mamifere::Mamifere(){
        printf("nouveau mamifere est nee\n");
        this->a=6;
    }

Mamifere::~Mamifere(){
        printf("mamifere Mort :(\n");
    }
void Mamifere::manger() {
    printf("hhhh   je mange maifere %d\n",Mamifere::getA());
    }
void Mamifere::avancer() const{
    printf("allez-y Mamifere\n");
}

Deufin::Deufin(){
    printf("nouveau Deufin  est nee\n");
}
int Mamifere::getA(){
    return this->a;
}
void Deufin::manger() const{
    printf("hhhh   je mange poisson\n");

}
void Deufin::avancer() const{

    printf("allez-y Deufin\n");
}

Deufin::~Deufin(){
    printf("Deufin Mort :(\n");
}



main.cpp





void exp031(){
    Mamifere f;//nouveau mamifere est nee   //   nouveau Deufin  est nee
    Deufin d;

    f.avancer();//allez-y Deufin (resolution dynamique des lien  la presence de mot cle virtual)
    f.manger();//hhhh   je mange maifere (resolution static des lien pas de mot cle virtual)
    printf("a=%d\n",d.getA());//Deufin Mort :(   mamifere Mort :( (resolution static des lien  la presence de mot cle virtual) distructeur de class fille appel auromatiquement le destructeur de la class mere


}

int main(){
    exp031();

    getchar();
    return 0;
}
Velarium answered 14/12, 2015 at 2:32 Comment(0)
K
0

Getters and setters do Not give you complete control over private data members. The control still lies with the base class.

Kilmarx answered 20/4, 2010 at 15:38 Comment(0)
V
0

Using the pattern

class MyClass {
  private: int a;
  public: void setA(int x) { a = x; }
  public: int getA() const { return a; }
};

seems object-orientated and has the sent of encapsulation.

However as you noticed, you can still directly access the private field and there is nothing gained over just making a public and accessing it directly.

Using getters and setters like this does not really make sense in C++.

Vinosity answered 20/4, 2010 at 15:43 Comment(5)
Actually they do. In C# (for example), if you decided to cache access to a here (assuming it actually was a lot of work to calculate a), you could just make a a property and you'd be done. However, in C++ you'd have to go and replace all code that references MyClass.a with MyClass.GetA();Shonda
This question is related to C++ not C#. And a lot of people think it is smart to provide generic getters and setters for integral types - but it is not.Vinosity
"Using getters and setters like this does not really make sense in C++.". Allowing unfettered access to data members except through a well defined interface (e.g. getters and setters) makes tracking down errors a nightmare. You need to look at all places where that member is set to try to determine why it has an unexpected value. Restricting access to class members through that well defined interface makes debugging much easier, as you have the stack trace providing some useful insight.Thorfinn
@andand: Or you could just learn to use your debugger better.Telson
This doesn't answer the question. It's just a rant about a personal opinion on programming style (and a factually incorrect conclusion, to boot).Snippy
B
0

If you want inherited private members to be modifiable in a child class, then that is possible if you make the child class a friend of the base class.

Buccal answered 17/7, 2024 at 10:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.