BlueMoon93 BlueMoon93 - 8 days ago 4
C++ Question

How to avoid re-declaring child methods and still define different methods for different child classes?

At the moment, I have a parent class and 2 child classes declared in

Setplay.h
, as such

namespace agent {

class Setplay {
public:
virtual int reset() {return 0;};
};

class ChildSetplay1 : public Setplay {
public:
virtual int reset();
};

class ChildSetplay2 : public Setplay {
public:
virtual int reset();
};

}


And in a
Setplay.cpp
, I define the methods

namespace agent {

int ChildSetplay1::reset(){
return 1;
}

int ChildSetplay2::reset(){
return 2;
}

}


Is there a way to avoid re-declaring the methods in the
.h
and still define unique methods for each child?


If I avoid re-declaring the methods in the
.h
:

namespace agent {

class Setplay {
public:
virtual int reset() {return 0;};
};

class ChildSetplay1 : public Setplay {};
class ChildSetplay2 : public Setplay {};

}


Then I get the following error:


error: no ‘int agent::ChildSetplay1::reset()’ member function declared in class ‘agent::ChildSetplay1’


But I can't define different methods for each child if I change the methods' signature to something like

int reset(){
return ??; // return 1? 2?
}


I'm not sure there is a way to do this, but my motives are:


  • the actual classes have several methods and re-declaring everything all the time looks ugly

  • I still need to keep everything inside the
    .cpp
    and
    .h



So, is it possible? Or are there better alternatives?

Answer

You need to define the function for every child, so you can't escape this. What you can do, is to go a little bit around and use a #define if you have multiple functions Like:

#define SET_PLAY_FUNCTIONS public:\
                           virtual int reset();\
                           virtual int go(); 
namespace agent {

class Setplay {
public:
    virtual int reset() {return 0;};
    virtual int go();
};

class ChildSetplay1 : public Setplay {
    SET_PLAY_FUNCTIONS
};

class ChildSetplay2 : public Setplay {
    SET_PLAY_FUNCTIONS
};

}

At least you can save something.....