Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Guru needed! problems with static members & inheritance

Status
Not open for further replies.

cansley4puss

Programmer
May 15, 2001
9
0
0
GB
Is there any way to get a base class's methods to operate on a derived class's static members? - ie

base class
f(){ number++ }

derived class
static int number

The only way of doing this I can find is to make the base class a class template and instantiate a version of the template instead of deriving - ie

class template base
static int number
f() { number++ }

instantiate template and initialise number

But this is messy and confusing. Does anyone know any other workaround for this?

Cheers, Ian.

 
class base_class
{
virtual int get_value(void)=NULL;
virtual void set_value(int)=NULL;
public:
void f(void);
};

void base_class::f(void)
{
set_value(get_value()+1);
}

class derived_class: public base_class
{
int number;

int get_value(void);
void set_value(int);
public:
int test(void);
};

int derived_class::get_value(void)
{
return(number);
}

void derived_class::set_value(int ii)
{
number=ii;
}

int derived_class::test(void)
{
number=1;
f();

return(number);
}

derived_class my_obj;

int main(void)
{
printf("%d\n", my_obj.test());

return(0);
}
 
I don't know if it is a good idea to let a base class operate on a derived class's member, but one workaround may look like this:

Code:
#include <iostream>

struct base {
  void f();
};

struct derived : public base {
  static int number;
};

void base::f() { derived::number++; }

int derived::number = 0;

int main() {
  base A;

  A.f(); A.f(); A.f();

  // output: &quot;3&quot;
  std::cout << derived::number << std::endl;
  return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top