Search code examples
c++inheritanceparent-childaccess-specifier

cpp inheritance (access parent data member value by child)


Is there a way to access data member values of the Parent by Child? Below example:

.h file:

#ifndef PRAC_H
#define PRAC_H
#include <iostream>
using namespace std;

class ToolFrame {
    public:
        string  mManuID;
        void    setManuID(string manu_id) { mManuID = manu_id; }
        string  getManuID() { return mManuID; }
};

class Hammer : public ToolFrame {
    int     mDurability;
    public:
        void    setDurability(int durability) { mDurability = durability; }
        int     getDurability() { return mDurability; }
};

.cpp file:

#include "prac.h" 

int main() {
    ToolFrame xz00;
    Hammer bonker100;

    xz00.setManuID("00a1d");
    bonker100.setDurability(50);
    cout << bonker100.getDurability() << endl;
    cout << bonker100.getManuID() << endl;

    return 0;
}

output: 50

output should be: 50 00a1d

issue: I understood "cout << bonker100.getManuID() << endl;" should access Parent's data member value (mManuID), as the member is not set to private. However, output is not the set value "00a1d".

question: cant children access parent's public value in this manner?

Tried different access specifiers, by moving Parent's data members from private to public. Set link between child and parent to public.


Solution

  • Child classes inherit properties and members, not values. Hammer instance bonker100 has inherited member mManuID and public (also protected, but there are none in this case) methods of a ToolFrame, but it has its member default-constructed. ToolFrame and Hammer objects are not the same - they are different pieces of data and don't share their values.