Virtual function call - c++

Here is my hierarchic of classes.
I have declare following abstract interface class, which have just one function:
class IAuthenticator
{
public:
virtual void CreateJson() = 0;
};
After I have created on more class 'UIData' and inherits it from interface class, in this case:
class UIData : public IAuthenticator
{
protected:
UIData() : mWindowHandle(0)
{ /* Constructor do nothing. **/ }
private:
integer mWindowHandle;
public:
void CreateJson()
{
std::cout<<"UIData::CreateJson\n";
}
};
I have one more class which inherits from UIData
class AuthenticateIn : public UIData
{
private:
string mOrigin;
string mLogoURL;
string mUserID;
public:
void CreateJson()
{
std::cout<<"AuthenticateIn::CreateJson\n";
}
};
Question
In my main function I have write code like this.
int main()
{
AuthenticateIn* ai = new AuthenticateIn();
ai->CreateJson();
}
When I call CreateJson() function I see log "AuthenticateIn::CreateJson". I want to find a way to call CreateJson() and it will be called for all base classes.
I know that I can do that calling this->UIData::CreateJson() from AuthenticateIn class CreateJson function, but is there any other way to do that, some automatic way ? Thanks !!

is there any other way to do that, some automatic way
No, there isn't. You have to call the base class's implementation from the derived class. The compiler won't do this automatically since it doesn't know whether you actually want this.

You have to call the base class function in the derived class sort of like this:
void CreateJson() {
UIData::CreateJSon();
}
etc

No, there is no such way. If you want to call virtual function from base class you should do this directly.

You may not be able to force a call to a virtual base class, but you can use indirection to simulate the behaviour.
typedef int integer;
#include <iostream>
#include <string>
using std::string;
using std::cout;
class IAuthenticator
{
public:
virtual void CreateJson() = 0;
};
class UIData : public IAuthenticator
{
protected:
UIData() : mWindowHandle(0)
{ /* Constructor do nothing. **/ }
private:
integer mWindowHandle;
virtual void CreateJsonPrivate() = 0;
public:
void CreateJson()
{
CreateJsonPrivate();
std::cout<<"UIData::CreateJson\n";
}
};
class AuthenticateIn : public UIData
{
private:
string mOrigin;
string mLogoURL;
string mUserID;
virtual void CreateJsonPrivate()
{
std::cout<<"AuthenticateIn::CreateJson\n";
}
};
int main()
{
AuthenticateIn* ai = new AuthenticateIn();
ai->CreateJson();
}
Output:
AuthenticateIn::CreateJson
UIData::CreateJson

Related

Creating List of abstract base class to fill with inherited objects

I want to create a List which is able to hold every Object I throw at it as long as they share the same ABSTRACT base class.
Here is an sample code of how I want to achieve this.
#include <iostream>
#include <memory>
#include <list>
class Observer
{
public:
virtual void update() = 0;
};
class RequestStateObserver
{
public:
void registerObserver(std::shared_ptr<Observer> o){
observerList.push_back(o);
}
private:
std::list<std::shared_ptr<Observer>> observerList;
};
class RestRequestCreator :Observer
{
void update() override;
};
void RestRequestCreator::update()
{
std::cout<<"RestRequestCreator::update()";
}
class dbHandler :Observer
{
void update() override;
};
void dbHandler::update() {
std::cout<<"dbHandler::update()";
}
int main()
{
RestRequestCreator rrc;
RequestStateObserver rso;
dbHandler dbhandler;
std::shared_ptr<RequestStateObserver> stateObserver;
std::shared_ptr<RestRequestCreator> rr_ptr = std::make_shared<RestRequestCreator>(rrc);
rso.registerObserver(rr_ptr);
rso.registerObserver(std::make_shared<Observer> (dbhandler));
}
o->registerObserver(std::make_shared<Observer> dbhandler)will tell me I can't create Observer since it's an abstract class which totally makes sense but
o->registerObserver(rr_ptr) will tell me it can't convert std::shared_ptr<Observer> to std::shared_ptr<RestRequestCreator>
I am at the moment not sure how to fix this problem or what exactly I should try next.
Would Templates help me? If I am correct they would just allow me to put as many objects of ONE child class into my List, if that's wrong please tell me and I will re-read about templates again.
The conversion fails because Observer is a private base of RestRequestCreator, and is inaccessible.
You'll need to use public inheritance for the compiler to implicitly convert from the derived class to the base:
class RestRequestCreator :public Observer
That fixes the immediate problem, but leaves the problems with make_shared<Observable> on the next line.
Also: should an observee co-own an observer? In general that would not be the case. Therefore, instead use regular pointers.
#include <list>
#include <iostream>
using std::cout;
class Observer
{
public:
virtual void update() = 0;
};
class ConcreteObserver : public Observer
{
public:
void update() override {
cout << "ConcreteObserver noticed update\n";}
};
class OtherKindConcreteObserver : public Observer
{
public:
void update() override {
cout << "OtherKindObserver noticed update\n";
}
};
class Subject
{
public:
void registerObserver( Observer* o) {
observerList.push_back( o);
}
void signalObservers() {
for ( auto observer : observerList)
observer->update();
}
private:
std::list<Observer*> observerList;
};
int main() {
ConcreteObserver observer1;
OtherKindConcreteObserver observer2;
Subject subject;
subject.registerObserver( &observer1);
subject.registerObserver( &observer2);
subject.signalObservers();
return 0;
}

How to pass a member function to a base class contructor?

I have a class structure that i want to use and i want to use a function of a derived class to be passed as a constructor argument to the base class. I cannot find the right syntax for it (new to C :))
This is the base class that i use and it has a constructor with a callback function:
class SPortSensor {
public:
SPortSensor(sensorData (*pCallback)(SPortSensor*));
sensorData getValue();
private:
sensorData (*getData)(SPortSensor*);
};
This is the derived class that implements the callback function within the class (pCallback) so it has a different constructor and a member function that needs to be passed to the base class constructor:
class SimpleSensor : public SPortSensor {
public:
SimpleSensor(int id);
long value;
private:
int _id;
sensorData pCallback(SPortSensor*);
};
This header compiles fine. The only error i am seeing is in the implementation of the SimpleSensor constructor. I cannot find the right syntax for this:
sensorData SimpleSensor::pCallback(SPortSensor* sensor) {
...
}
SimpleSensor::SimpleSensor(int id) : SPortSensor(pCallback) {
_id = id;
}
Googling this issue didn't help that much since i probably don't use the right search words and don't understand enough of c++ (i am a C# guy).
The circular reference smells like there might be some general ownership issues.
But, one way around your impass is to use std::function<sensorData(SPortSensor*)> instead of the function pointers. Then initialize the base class with a lambda pointing to itself:
SimpleSensor(int id) : SPortSensor([this](SPortSensor* sps) { return pCallback(sps); }) { }
I cannot in good concious condone this, but it didn't explode when I tried it. One caveat is that SimpleSensor won't be initialized when the base constructor is called, so SPortSensor can't call the lambda in its own constructor.
Call-backs usually take place between different objects. One solution is to differ the use of the derived class method after constructor (in an init method for example?), and declare the method as virtual.
#include <iostream>
struct sensorData {
double val = 0;
};
class SPortSensor {
public:
virtual sensorData getValue() {
std::cout << "Base class\n";
sensorData sd;
return sd;
}
};
class SimpleSensor : public SPortSensor {
public:
long value;
SimpleSensor(int id): id(id) {
}
virtual sensorData getValue() {
std::cout << "Derived class\n";
sensorData sd;
return sd;
}
private:
int id;
};
int main() {
SPortSensor base;
SimpleSensor derived(1);
base.getValue();
derived.getValue();
SPortSensor* derivedPtr = new SimpleSensor(2);
derivedPtr->getValue();
return 0;
}
So i think the complexity (issue?) was in trying to do thing with to few lines of code. I simply switched to polymorphy with a abstract class to simplify things.
Abstract base:
class SPortSensor {
public:
void (*valueSend)(void);
virtual sensorData getData () = 0;
};
2 implementation classes:
class CustomSPortSensor : public SPortSensor {
public:
CustomSPortSensor(sensorData (*callback)(CustomSPortSensor*));
private:
sensorData (*_callback)(CustomSPortSensor*);
virtual sensorData getData(){
return _callback(this);
}
};
class SimpleSPortSensor : public SPortSensor {
public:
SimpleSPortSensor(int id);
long value;
private:
int _id;
virtual sensorData getData(){
sensorData data;
data.sensorId = _id;
data.value = value;
return data;
}
};
This now works as expected and is very easy to use and understand (usage of the implementation must as readable as possible).
Now i only want the implementation of the virtual functions to be in the .cpp instead of the .h.......

Calling an Interface function from multiple different implementing classes c++

Hi I am trying to implement an interface in C++. I want to be able to call a function from a class that could be implemented by various different classes. The approach I have tried fails since I cannot call the function with a pointer to the interface (abstract class). Here is the basic gist of the code I have tried:
Interface class:
class InterfaceClass{
virtual void handle() = 0;
};
Calling class:
CallingClass::CallingClass(InterfaceClass * owner){
this->owner = owner;
}
void CallingClass::doStuff(){
owner->handle();
}
Implementing classes:
class Class1 : public InterfaceClass {
public:
Class1();
void handle();
}
class Class2 : public InterfaceClass {
public:
Class2();
void handle();
}
each of the handle() functions in the implementing classes just prints out the class name. Each implementing class contains an object of the CallingClass which calls doStuff in a separate timer thread. I am trying to keep it so that the CallingClass doesnt need to know anything about the classes that implement the handle() function.
It fails since I cannot call the function of an abstract class. I expected this but cant figure a way around it. Any advise would be much appreciated! Let me know if any more information is needed.
Thanks
you were missing the public: keyword in the Interface class.
you need to remember that C++ class are by default private, so you should add public where it is needed.
this is a working example for you:
class InterfaceClass {
public:
virtual void handle() = 0;
};
class Calling{
public:
Calling(InterfaceClass * owner) {
this->owner = owner;
}
void doStuff() {
owner->handle();
}
~Calling() { delete owner; }
private :
InterfaceClass* owner;
};
class Class1 : public InterfaceClass {
public:
void handle() override
{
std::cout << "Class1"<<std::endl;
}
};
class Class2 : public InterfaceClass {
public:
void handle()
{
std::cout << "Class2" << std::endl;;
}
};
int main(int argc, char** argv)
{
Calling c1(new Class1());
c1.doStuff();
Calling c2(new Class2());
c2.doStuff();
}

Is it possible to save pointer to function member from a derived in another class used by a base class

Basically I have a class let's say Parameter that has a get and set variable.
I also have a base class let's say Vehicle that has a method registerParameter(...) that takes a pointer to function member as getter and a pointer to function member as setter. This method is then supposed to write those two pointers into an object of the parameter class and throws this object into a vector.
And last but not least we have a derived class let's say Car and we call registerParameter(...) with the string "color" as parameter name and a getter and setter from this derived class.
Example in code:
Parameter file
#ifndef BASE_H
#define BASE_H
#include "base.h"
class Parameter
{
std::string (Base::*get)();
void (Base::*set)(std::string);
};
#endif
Base file
#ifndef PARAMETER_H
#define PARAMETER_H
#include <vector>
#include "parameter.h"
class Base
{
public:
std::vector<Parameter> list;
void registerNew(std::string (Base::*get)(), void (Base::*set)(std::string))
{
Parameters parameter;
parameter.get = get;
parameter.set = set;
list.push_back(parameter);
}
};
#endif
Derived file
class Derived
{
public:
Derived derived()
{
registerNew(&getColor, &setColor);
}
std::string getColor()
{
return this->color;
}
std::string setColor(std::string newColor)
{
this->color = newColor;
}
private:
std::string color;
};
I've been thinking about this for days now and I really need the solution until friday evening.
You cannot do what are trying:
The types std::string (Base::*)() and std::string (Derived::*)() are very different. std::string (Derived::*)() cannot be auto converted to std::string (Base::*)().
Take the following scenario.
struct Base
{
int foo() { return 10; }
};
struct Derived : Base
{
int bar() { return 20; }
};
int main()
{
Base base;
int (Base::*bf)() = &Base::foo;
(base.*bf)(); // Should be able to call Base:foo(). No problem.
bf = &Derived::bar; // This is a compiler error. However, if this were allowed....
(base.*bf)(); // Call Derived::bar()?? That will be a problem. base is not an
// instance of Derived.
}
Update
You can do something like:
#include <string>
#include <vector>
class Base;
// Create a base class Functor that provides the interface to be used by
// Base.
struct Functor
{
virtual ~Functor() {}
virtual std::string get(Base& base) = 0;
virtual void set(Base& base, std::string) = 0;
};
// Create a class template that implements the Functor interface.
template <typename Derived> struct FunctorTemplate : public Functor
{
// typedefs for get and set functions to be used by this class.
typedef std::string (Derived::*GetFunction)();
typedef void (Derived::*SetFunction)(std::string);
// The constructor that uses the get and set functions of the derived
// class to do itw work.
FunctorTemplate(GetFunction get, SetFunction set) : get_(get), set_(set) {}
virtual ~FunctorTemplate() {}
// Implement the get() function.
virtual std::string get(Base& base)
{
return (reinterpret_cast<Derived&>(base).*get_)();
}
// Implement the set() function.
virtual void set(Base& base, std::string s)
{
(reinterpret_cast<Derived&>(base).*set_)(s);
}
GetFunction get_;
SetFunction set_;
};
class Base
{
public:
std::vector<Functor*> functorList;
void registerFunctor(Functor* functor)
{
functorList.push_back(functor);
}
};
class Derived : public Base
{
public:
Derived()
{
// Register a FunctorTemplate.
registerFunctor(new FunctorTemplate<Derived>(&Derived::getColor,
&Derived::setColor));
}
std::string getColor()
{
return this->color;
}
void setColor(std::string newColor)
{
this->color = newColor;
}
private:
std::string color;
};
Your base class should know the derived class. That sounds complex but the problem has been solved already:
template<typename DERIVED> class Base
{
public:
class Parameter {
std::string (DERIVED::*get)();
void (DERIVED::*set)();
};
private:
std::list<Parameter> list;
// ...
};
class Derived : public Base<Derived> // !!!
{
registerNew(&Derived::getColor, &Derived::setColor);
};
This solution is known as the Curiously Recurring Template Pattern (CRTP).

Polymorphism: How do you access derived class member functions?

Let's say we have a derived class from an abstract base class. A pointer to the abstract base class is declared in the main and allocated to the derived class through "new". How do you access the member functions of the derived class from a pointer to the base class (not from an object of the derived class)?
Example:
#include <iostream>
using namespace std;
class clsStudent
{
public:
virtual void display() = 0;// {cout<<"Student\n";}
};
class clsInternational : public clsStudent
{
public:
void display(){cout<<"International\n";}
void passportNo(){cout<<"Pass\n";}
};
class local : public clsStudent
{
public:
void display(){cout<<"International\n";}
void icNo(){cout<<"IC\n";}
};
int main()
{
clsStudent * s = new clsInternational;
clsStudent * s2 = new local;
s->display();
s->passportNo(); //This won't work
return 0;
}
Cheeky answer: don't. I mean, if you really need to, the answer to your technical question is the dynamic_cast operation in C++, in order to a conduct a "downcast" (cast from base to derived class).
But stepping back, this is a reasonable use case for a virtual function. Ask yourself, what is the common meaning I want to access?
In this case, we want all students to have an identifying number.
Working source code: http://ideone.com/5E9d5I
class clsStudent
{
public:
virtual void display() = 0;// {cout<<"Student\n";}
virtual void identifyingNumber() = 0;
};
class clsInternational : public clsStudent
{
public:
void display(){cout<<"International\n";}
void identifyingNumber(){cout<<"Pass\n";}
};
class local : public clsStudent
{
public:
void display(){cout<<"Local\n";}
void identifyingNumber(){cout<<"IC\n";}
};
int main()
{
clsStudent * s = new clsInternational;
clsStudent * s2 = new local;
s->display();
s->identifyingNumber();
s2->display();
s2->identifyingNumber();
return 0;
}