Search code examples
c++classinheritanceargumentsvirtual

Is there a way that I can access the values in the base class using the derived class?


I'm using c++ and i have no idea on how can i access the variables in my base class using the derived class. I need to get the values in the base class and do an operation in the derived class, since all the functions in the base class contains arguments, when I call the function,

ex:

Baseclass.getvalue();

i can't put any arguments since it is not defined.

I already did the constructor parts like

class derivedclass:baseclass
{
//insert functions here.
};

derivedclass::derivedclass()
     :baseclass()
{
 //insert initialization here
}

but i still can't access the values. help? do i need to use virtual? if yes, how?

*this is a user-defined program


Solution

  • simply access the (public or protected) values as if they were part of your derived class.

    class baseclass {
      protected:
          int m_value;
      public:
           baseclass();
           virtual int getvalue();
    };
    
    class derivedclass : public baseclass {
      void dosomething(void) {
         // whoa: `m_value` is part of `baseclass`, and we can simply access it here!
         std::cout << "value: " << m_value << std::endl;
    
         // we can also use `getvalue()`
         std::cout << "getvalue(): " << getvalue() << std::endl;
      }
    };