1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Inheritance

Discussion in 'C++' started by freakyboard, Jan 1, 2011.

  1. freakyboard

    freakyboard New Member

    Joined:
    Jan 1, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    class x{int a;};
    class y:public x{};
    main(){y k;  k.a=3; }
    
    How can I access "k.a"?
    PS: You can't change or omit any part of the code.
    a have to be private.
    Member access specifier have to be public ( class y::public x ).
    You can add functions to x class but you can't add data members to x class.
    You can add functions to y class too.
    -> Maybe we need to type a friend function.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Add a public get and set function to x, which will be inherited by y:
    Code:
    class x
    {
    private:
      int a;
    
    public:
      int get_a() { return a; }
      void set_a(int new_a) { a=new_a; }
    };
    
     
    shabbir likes this.

Share This Page