Question

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

Was it helpful?

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;
  }
};

OTHER TIPS

In this case, the inheritance is private, so the base subobject and its members are only accessible within the derived class and its friends. By default, members and base classes are private if the class definition is introduced with the class keyword, and public with the struct keyword. If you want to access them from outside, then you'll need public inheritance:

class derivedclass : public baseclass {/*...*/};

or

struct derivedclass : baseclass  {/*...*/};

If the derived class doesn't hide the member by declaring a member with the same name, you can access it as if it were a member of the derived class. (If the inheritance is protected or private, then it will be protected or private within the derived class, and so may not be accessible).

If it is hidden, and you specifically want the base-class version, then you'll need to qualify the member name:

Derived.baseclass::getvalue()

but if this is the case, then there's something funky going on and the class interfaces probably need rethinking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top