How to properly override function with different arguments in derived class? - c++

I'm making a simple MVC example for c++ classes at my uni. First, look at the code:
The executor.h part:
class IExecutor {
IParams params;
public:
virtual void initialize(IParams iParams);
virtual void execute();
};
class QEExec : public IExecutor {
public:
void initialize(QEParams iParams) override;
void execute() override;
};
And now params.h part:
class IParams {
};
class QEParams : public IParams {
public:
int a;
int b;
int c;
};
The problem is that I want to create void initialize(QEParams iParams) function for QEExec and pass QEParams to it in order to have access to a, b, and c parameters (I'll need that later) but I can't do so because of virtual void initialize(IParams). I thought that if QEParams is derives from IParams I will be able to do so, but I can't access parameters that I mentioned earlier. How to make it work so that I'll be able to access a, b and c parameters in initialize function?
EDIT: I'll put a photo of how it should look like:
https://i.stack.imgur.com/KWaSQ.jpg

Interface doesn't have any fields
Interface has only pure virtual methods
Name initialize of IExecutor indicates some misunderstanding. Looks like it suppose to be called once at the begging during construction time. It should be hidden in step where some factory creates object implementing IExecutor
So basically I'm suspecting you need more something like this:
class IExecutor
{
public:
virutal ~IExecutor() {}
virtual void execute() = 0;
};
struct QEParams {
int a;
int b;
int c;
};
class QEExec: public IExecutor
{
public:
QEExec(int b, int c) ....
void initialie(); // second step init
void execute() override;
};
class CAExec: public SomeOtherBaseClass, public IExecutor
{
public:
CAExec(int a, int c) ....
void execute() override;
};
std::unique_ptr<IExecutor> executorFactory(const QEParams& params)
{
if (params.a < 0) {
auto result = std::make_unique<QEExec>(params.b, params.c);
result->initialie();
return result;
}
return std::make_unique<CAExec>(params.a, params.c);
}
Usually factory parameters are structural data and extra abstraction is obsolete.
If different kind of arguments are needed to create alternative version of IExecutor you just provide different factory function (possibly overload):
std::unique_ptr<IExecutor> executorFactory(const std::string& fileName)
{
....
}

It sounds like you're using OOP incorrectly.
Since QEExec is a IExecutor (it inherits), and it can initialize just like IExecutor can, ideally, both of those initialize's will be doing similar things to their IParams objects. If so, then the one who should be acting on a, b and c should be QEParams, not QEExec.
You could do this with polymorphism like:
class IParams {
virtual void init_logic() { }
};
class QEParams : public IParams {
public:
void init_logic() { /* Do something with a/b/c */ }
private:
int a;
int b;
int c;
};
And then...
class IExecutor {
IParams params;
public:
virtual void initialize(IParams *iParams);
virtual void execute();
};
class QEExec : public IExecutor {
public:
//Will call the QEParams init_logic when passed a QEParams pointer
void initialize(IParams *iParams) { iParams->init_logic(); }
void execute() override;
};

Related

How to create uniform interface to build for builders in builder patterns, if one of concrete builders take extra argument?

class Builder
{
public:
virtual void Build(int a) = 0;
};
class ConcreteBuilder1 : public Builder
{
public:
void Build(int a);
};
class ConcreteBuilder2 : public Builder
{
public:
void Build(int a. struct A* a);
};
So My question is how to design Build() method to take both parameters(int, struct* A). But with same builder interface ?
So that,
int x;
struct A* y;
Builder concrteBuilder1 = new ConcreteBuilder1();
concrteBuilder1 ->Build() // // Here I am forced to pass struct A* a eventhough not needed for concerte builder1 . And I am also forced to forced to change Builder interface too.
My apologies if I did not convey the question clearly.
Builder usually builds an object of another class. You may try something similar to this:
class ToBuild
{
//some code here
};
class Builder
{
public:
virtual ToBuild * build() = 0;
};
class ConcreteBuilder : public Builder
{
int _valA;
int _valB;
public:
ToBuild * build() override
{
ToBuild * obj = new ToBuild();
//initalize obj using _valA and _valB variables;
return obj;
}
ConcreteBuilder& valA(const int val)
{
_valA = val;
return *this;
}
ConcreteBuilder& valB(const int val)
{
_valB = val;
return *this;
}
};
int main()
{
ConcreteBuilder b;
ToBuild * obj = b.valA(1).valB(2).build();
//some code
delete obj;
return 0;
}
[edit]
You can write another derived class with as many parameters as you want and still use a single 'build' method.
Add
using Builder::Build;
to the derived class's declarations. This will import this symbol into the derived class, and make both it, and the derived class methods, of the same name, available to overload resolution. I.e.
using Builder::Build;
void Build(int a);
I'm ignoring the fact that you can't construct the derived class anyway, since it fails to implement this pure virtual function from the base class.
Derived class override their functions from the one which has same parameters and same return value.
So if you declare a function like...
class Builder
{
public:
virtual void Build() = 0;
};
class ConcreteBuilder1 : public Builder
{
public:
void Build(int a);
};
class ConcreteBuilder2 : public Builder
{
public:
void Build(int a. struct A* a);
};
Here, Build function in ConcreteBuilder1 class treated as a new function, not override function.
So try this.
class Builder
{
public:
virtual void Build(int a, A* b = 0) = 0;
};
class ConcreteBuilder1 : public Builder
{
public:
void Build(int a);
};
class ConcreteBuilder2 : public Builder
{
public:
void Build(int a, struct A* a);
};
I wish it's helpful for you.

Defining a virtual method inherited more than once

I've been trying to find an answer to this question but I couldn't (I don't even know how to properly formulate this) so I decided to write my first post ever on StackOverflow =).
The context is the following:
I have this parent class:
class Parent
{
public:
Parent(){};
void foo(void)
{
//Do some common things
bar();
//Do some more common things
};
protected:
virtual void bar(void) = 0;
};
And I want to create an indefinite amount of derived Childs:
class Child1 : public Parent
{
public:
Child1() : Parent(), child1Variable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t child1Variable;
};
class Child2 : public Parent
{
public:
Child2() : Parent(), child2Variable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t child2Variable;
};
.
.
.
class ChildN : public Parent
{
public:
ChildN() : Parent(), childNVariable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t childNVariable;
};
The reason being mainly not repeating the code in Parent's foo()
Then I would like to create my final instantiable classes as, for instance:
class ExampleFinal : public Child1, public Child3, public Child27
{
//How to define Child1::bar(), Child3::bar() and Child27::bar() ??
private:
void bar(void); //????
};
So the questions are:
How can I define the method for (abusing notation) ExampleFinal::Child1::bar, ExampleFinal::Child3::bar, ...
Am I so stuck on this that I'm overlooking a much simpler solution?
The final goal is being able to do something like:
ExampleFinal test;
test.Child1::foo(); //should end up on "ExampleFinal::Child1::bar"
test.Child3::foo(); //should end up on "ExampleFinal::Child3::bar"
Thanks!
Implementing ExampleFinal::bar() (side-note: bar(void) is a C-ism which has no use in C++) will override all of the bars you have declared at once. If you want to have different versions, you'll need to interpose another layer of classes:
struct GrandChild1 : Child1 {
void bar() override { /*...*/ }
};
// And so on...
struct ExampleFinal : GrandChild1, GrandChild3, GrandChild27 {
// Nothing needed here.
};
Then the behaviour you described will work. Be aware, though, that your inheritance graph means that an ExampleFinal has one Parent subobject per Child. This is not an issue in itself but might not model what you want -- maybe you need virtual inheritance here, but beware of the rabbit hole.
If you want to keep the overrides for all ChildN::bars inside ExampleFinal, you can add tag-dispatching to discern them, at the cost of one more virtual call:
struct Parent {
void foo() {
bar();
};
protected:
template <class Child>
struct tag { };
virtual void bar() = 0;
};
struct Child1 : Parent {
protected:
virtual void bar(tag<Child1>) = 0;
void bar() final override {
return bar(tag<Child1>{});
}
int child1Var;
};
struct Child2 : Parent {
protected:
virtual void bar(tag<Child2>) = 0;
void bar() final override {
return bar(tag<Child2>{});
}
int child2Var;
};
struct ExampleFinal : Child1, Child2 {
protected:
using Parent::tag;
void bar(tag<Child1>) final override {
std::cout << "Child1::bar\n";
}
void bar(tag<Child2>) final override {
std::cout << "Child2::bar\n";
}
};
Note that the bar() to bar(tag<ChildN>) bridge can easily be hidden behind a macro. If you want to avoid the cost of the second virtual call, a CRTP can also be applied here.

How to mock constructors and destructor with gmock

I need to count how many times constructors(default/copy/move) and destructor have been called. I use gmock. How can i check it?
EDIT: Thanks to Marko Popovic suggestion i will explain that i have for now. I have a class like this, and i want to mock it with gmock. How can i do this?
class A
{
public:
static int m_calls_to_cons;
public:
A( ) { m_calls_to_cons++; }
};
int A::m_calls_to_cons;
I use this class to check behavior of my container.
First, you must specify what you need. The way to do this is by defining interface class:
class SpecialFunctionsNotifier
{
public:
virtual ~SpecialFunctionsNotifier() {}
virtual void construct() = 0;
virtual void destruct() = 0;
virtual void copyConstruct() = 0;
virtual void copyAssign() = 0;
};
So, you can make "default" null (meaning empty) object implemention:
class SpecialFunctionsNullNotifier : public SpecialFunctionsNotifier
{
public:
virtual void construct() override {}
virtual void destruct() override {}
virtual void copyConstruct() override {}
virtual void copyAssign() override {}
};
And, have A use of it:
class A
{
public:
static SpecialFunctionsNullNotifier m_calls_to_cons_default;
static SpecialFunctionsNotifier* m_calls_to_cons;
public:
A( ) { m_calls_to_cons->construct(); }
};
SpecialFunctionsNullNotifier A::m_calls_to_cons_default;
SpecialFunctionsNotifier* A::m_calls_to_cons = &A::m_calls_to_cons_default;
Then, mocking this notifies is easy task:
class SpecialFunctionsNotifierMock : public SpecialFunctionsNotifier
{
public:
MOCK_METHOD0(construct, void());
// ..
};
And in your tests, use in this way:
TEST(ACase, AConstructCount)
{
SpecialFunctionsNotifierMock callToConsMock;
A::m_calls_to_cons = &callToConsMock;
EXPECT_CALL(callToConsMock, construct()).Times(100);
A a[100];
// remember to cleanup
A::m_calls_to_cons = &A::m_calls_to_cons_default;
}

C++: Call child static method from parent

Simply, I need to do as the title says: Call a child static method from parent. The problem is that I don't know the child class name in the parent as there could be multiple children. The static method needs to stay static. For example:
class A{ // parent class
public:
void process(){
getData(); // <-- Problem
}
}
class B: public A{ // child class
static int getData();
}
void main(){
B b;
b.process();
}
One solution that comes to mind is to have a virtual method that calls the static method. This would not be very nice and it would mean I would have to implement the method for every child I have:
class A{ // parent class
virtual int getDataFromStaticMethod() = 0;
public:
void process(){
getData(); // <-- Problem
}
}
class B: public A{ // child class
static int getData();
virtual int getDataFromStaticMethod(){
return B::getData();
}
}
void main(){
B b;
b.process();
}
But I really wish it was possible to implement a pure virtual method with a static method:
class A{ // parent class
virtual int getData() = 0;
public:
void process(){
getData(); // <-- Problem
}
}
class B: public A{ // child class
static int getData();
}
void main(){
B b;
b.process();
}
Any suggestions?
Thanks!
You could use templates.
template<typename TChild>
class A
{
typedef TChild child_type;
public:
void process()
{
child_type::getData();
}
};
class B: public A<B>
{
static int getData();
};
class C: public A<C>
{
static int getData();
};
int main(int argc, char** argv)
{
B b;
b.process();
C c;
c.process();
}
Note:
If you want to hold static state in your base class, or if you need to hold a collection of base class objects, then you would need an additional layer:
class ABase
{
//any static state goes here
public:
virtual int process() = 0;
};
template<typename TChild>
class A: public ABase
{
typedef TChild child_type;
public:
int process()
{
child_type::getData();
}
};
class B: public A<B>
{};
std::vector<ABase*> a_list;
Assuming the signature of the child functions are all identical, you could initialize your base class object to hold a pointer to the child's version of the getData() function, e.g.:
class A {
int (*d_getData)();
protected:
explicit A(int (*getData)()): d_getData(getData) {}
public:
void process() {
int data = (this->d_getData)();
// ...
}
};
Obviously, the child classes would need to provide the corresponding constructor argument:
class B: public A {
static int whatever();
public:
B(): A(&whatever) {}
// ...
};
That's sort of an implementation of a per object overridable virtual function.
You can use virtual wrappers around the static function. E.g.
class A{ // parent class
// don't make pure virtual if you don't want to define it in all child classes
virtual int getData() { return 0 };
public:
void process(){
getData();
}
}
class B: public a{ // child class
static int do_getData();
int getData() { return do_getData(); }
}

C++ Inheritance problem

I have a class as follows:
Class A
{
virtual int doSomethingCool() = 0;
};
Class B : public A
{
int doSomethingCool();
};
Now the problem likes , I have a set of classes whcih are dependent on A as interface. I need to change the prototype of the function for one of the derived classes. i.e. i need to pass it a parameter.
Class C: public A
{
int doSomethingCool(int param);
};
Any suggestions how i can achieve this ?
No, you don't need to add it to the base class.
class A
{
public:
virtual int doSomethingCool() = 0 {}
};
class B : public A
{
public:
int doSomethingCool() {return 0;}
};
class C: public A
{
private:
int doSomethingCool(); // hide base class version!
public:
int doSomethingCool(int param) {return param;}
};
You can still call doSomethingCool() if done through a base class pointer:
C c;
//c.doSomethingCool (); // doesn't work, can't access private member
c.doSomethingCool (42);
A &a = c;
a.doSomethingCool ();
//a.doSomethingCool (42); // doesn't work, no member of A has that signature
Add it to the interface and default it to call the existing method. You don't have to do the default but don't make it pure otherwise all derived classes will have to implement. It might be better to leave it undefined or to throw. Depends on what you want to achieve.
class A
{
public:
virtual int doSomethingCool() = 0;
virtual int doSomethingCool(int param) {doSomethingCool()};
};
Make the function doSomethingCool() take the int parameter in A.
class A
{
public:
virtual void doSomethingCool(int param) = 0;
};
There's no problem. You can do it. The only caveat is that it will not be treated as an override of the base class virtual function.
class A
{
public:
virtual void doSomethingCool() = 0;
};
class B : public A
{
public:
void doSomethingCool();
};
class C: Public A
{
public:
void doSomethingCool(int param);
};
int main(){}
So while technically possible, you may really want to relook at the design of your interface class A.
One option may be to provide a default argument to A::doSomethingCool
virtual void doSomethingCool(int = 0) = 0;
This isn't syntactically correct C++.
No you can't change a prototype. How would it be used? What would be the value of the param if the non-parametric version would be called?
I would have introduced another, more specific, interface:
struct A
{
virtual int doSomethingCool() = 0;
};
struct A_specific : A
{
virtual int doSomethingCoolWithThis(int i) = 0;
};
class ConcreteA : public A
{
int doSomethingCool() { return 0; }
};
class ConcreteA_specific : public A_specific
{
int doSomethingCool() { return 0; }
int doSomethingCoolWithThis(int param) { return param; }
};
Then I would program to the correct interface:
int main()
{
const A& a1 = ConcreteA();
const A_specific& a2 = ConcreteA_specific();
a1.doSomethingCool();
a2.doSomethingCool();
a2.doSomethingCoolWithThis(2);
}
Just to give you another idea ;-)
Good luck!