24

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

shreyasva
  • 13,126
  • 25
  • 78
  • 101
  • 12
    A derived class *does* inherit private data members. – Agnel Kurian Apr 20 '10 at 15:36
  • 2
    What is even more confusing is that you can override private virtual functions of the base-class. – Björn Pollex Apr 20 '10 at 15:38
  • 1
    @Space_C0wb0y: That's not confusing at all. It's called the Template Method Pattern (which unfortunately has nothing to do with C++ templates) – Billy ONeal Apr 20 '10 at 15:41
  • 2
    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. – Mark B Apr 20 '10 at 15:47

7 Answers7

40

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.

Avi
  • 19,934
  • 4
  • 57
  • 70
  • 1
    @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. – David Thornley Apr 20 '10 at 15:42
  • 5
    @user265260: That might work on *your* platform, but it is never **required** to work. Ever. – Billy ONeal Apr 20 '10 at 15:42
  • just to poke and hack around, i was just wondering how this is implemented – shreyasva Apr 20 '10 at 15:43
  • 2
    Yes, you could manipulate the private data in a hackish, non-portable way using `this` and offsetting accordingly. – Emile Cormier Apr 20 '10 at 15:44
  • 1
    @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. – Emile Cormier Apr 20 '10 at 15:50
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
JRL
  • 76,767
  • 18
  • 98
  • 146
4

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

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • 2
    my doubt is how come you can manipulate the values of the private data members since clearly you cannot inherit them – shreyasva Apr 20 '10 at 15:36
  • 1
    and those getters and setters are members of the base class, so they have access to the private data. – amertune Apr 20 '10 at 15:37
  • 3
    @user235230: "clearly you cannot inherit them" This is WRONG. – John Dibling Apr 20 '10 at 15:53
  • 5
    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. – David Apr 20 '10 at 15:55
  • thank you @David this is the thing i needed to convince myself – Aayush Neupane Jul 23 '20 at 02:52
4

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).

csg
  • 8,096
  • 3
  • 14
  • 38
Kotauskas
  • 1,239
  • 11
  • 31
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;
}
Kotauskas
  • 1,239
  • 11
  • 31
mr.trovaz
  • 21
  • 2
0

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

zmbush
  • 2,790
  • 1
  • 17
  • 35
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++.

Danvil
  • 22,240
  • 19
  • 65
  • 88
  • 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();` – Billy ONeal Apr 20 '10 at 15:52
  • 1
    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. – Danvil Apr 20 '10 at 15:56
  • 1
    "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. – andand Apr 20 '10 at 16:09
  • @andand: Or you could just learn to use your debugger better. – John Dibling Apr 20 '10 at 17:00
  • 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). – SO_fix_the_vote_sorting_bug Dec 06 '19 at 23:42