Question

I have an doubt, with C++ redefinition. I assign memory in Derived class, so I need that this memory is reserved in Base class. So, I need considered that the attibute in the Base class is the same that the attribute in the Derived class, and I don't know is that is possible in C++.

class Base {
 protected:
  float * a;
  Base() {}
 public:
  virtual void reset() {
    a = 0;
  }  
  virtual void exec() {
    printf("Memory a: %x\n",a);
  }
};  

class Derivada: virtual public Base {
 protected:
  float * a;
  Derivada() {}
  virtual void reset() {
    a = new float[256];
  }
};

int main() {
  Derivada *hija= new Derivada();    
  hija->reset();
  hija->exec();
  delete hija;
}

I really need do overloading, because it is an example of my real problem. I have the same test (Derived an main, code), for two different class Base, one in each branch, of my two branchs, of CVS.

In one of this class Base, I have this attributes, an in the other class Base, I don't have this attributes, so I have to put it, in Derived class, for compiling.

I wouldn't like to have to make two different test codes, so I need override the attribute

Was it helpful?

Solution

You could do something like this (but requires C++11):

#include <type_traits>

// A way to check for 'attr' data member presence/absence using SFINAE
template<class T> constexpr auto missing_attr(T) -> decltype(T::attr, bool())
{
  return false;
}
constexpr bool missing_attr(...) { return true; }

struct Base { /* There might be (or not) a float data member 'attr' */ };

template<bool> struct Inject;
template<> struct Inject<true> { float attr = 0.0; };
template<> struct Inject<false> {};

struct Derived : public Base, protected Inject<missing_attr(Base())>
{
  void do_something_with_attr()
  {
    // Derived has only one 'float attr' (it can be from Base or from Inject).
    a *= a;
  }
};

There are other ways to detect if a data member exists, e.g. the member detector idiom (C++03 compatible).

OTHER TIPS

Do not redeclare the member the the derived class. The word "protected" ensures visibility.

If you redeclare the member, you will have a new member. This is called shadowing. See, e.g.

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