Thread: How do you Access base variable from class outside the hierarchy?

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    19

    Question How do you Access base variable from class outside the hierarchy?

    How do you access a variable from a base class outside the class hierarchy?

    example:
    Code:
    class Base
    {
        ...
        int x;
    }
    
    class Sub : public Base
    {
        ...
        void method1(Sub* sub); //this method can pass it self
        //to a method2 in class wantsToAccessX
    }
    
    class wantsToAccessX
    {
        ...
        void method2(Sub* sub) //method that looks at variable x
    }
    Now the variable x is accessable from class Sub, but i cant figure out how to access x from the other class wantsToAccessX. Have tried things like sub.x and sub->x.

    It the only way to do this with a getterMethod in class Sub?

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    It needs to be in public section, but in fact, you should never do this.
    Code:
    class Base {
    public:
        int x;
    };
    Code:
    class Base
    {
        ...
        int x;
    }
    
    class Sub : public Base
    {
        ...
        void method1(Sub* sub);
        void method2();
    }
    
    class wantsToAccessX
    {
        ...
    }
    Much better.
    Last edited by kmdv; 04-07-2011 at 08:27 AM.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    19
    Thanks kmdv,

    After reading your response i could see that it was better with a simpler approach. But it will be necessary in my program to do this at some time - giving an object the responsibility to alter another objects state. I found something about friend classes, i think this is the key.

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Why not add public setX()/getX() functions?
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Derived class doesn't see base class function
    By ejubenville in forum C++ Programming
    Replies: 2
    Last Post: 11-11-2009, 01:56 PM
  2. inheritance
    By Aisthesis in forum C++ Programming
    Replies: 8
    Last Post: 09-27-2009, 03:35 AM
  3. Access to members of protected base class
    By DL1 in forum C++ Programming
    Replies: 13
    Last Post: 07-20-2009, 10:30 AM
  4. Base class initialization
    By VirtualAce in forum C++ Programming
    Replies: 4
    Last Post: 01-11-2004, 04:52 AM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM