views:

88

answers:

2

When inheriting classes in C++ I understand members are inherited. But how does one inherit the methods as well?

For example, in the below code, I'd like the method "getValues" to be accessible not through just CPoly, but also by any class that inherits it. So one can call "getValues" on CRect directly.

class CPoly {
  private:
    int width, height;
  public:
    void getValues (int* a, int* b)
      { *a=width; *b=height;}
  };

class CRect: public CPoly {
  public:
    int area ()
      { return (width * height); }
  };

In other words, is there any way to inherit methods for simple generic methods like getters and setters?

+5  A: 

You can call getValues by using CRect, because getValues is inherited. The term "methods" is not defined by C++. If you refer to non-static member functions - they are members and are inherited to derived classes.

Your error is not that getValues isn't inherited, but that you try to access the inaccessible members width and height.

Johannes Schaub - litb
Wow thanks for the quick response! Changing from private to protected allowed the CRect to work as expected:
Pat
A: 

Everything is inherited, there is no distinction between member variables and member functions in this respect.

In CPoly if you want people who use your class to see the members (whether functions or variables) you use public. For the classes that derive from CPoly if you want them to be able to use the members (whether functions or variables), then you must make them either public or protected.

In the derived type CRect, when you specify the base class, you also must specify a default access member for all of the inherited members (whether functions or variables). if you specify public, all of the members inherited that are public will remain public. If you specify protected, all of the members inherited that are public or protected will be protected. If you specify private, all of the members inherited will become private.

Brian R. Bondy