Pointer to Class Member functions [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store class member function address, to local data structure(table)
typedef struct
{
unsigned int id;
void (TCLASS::*proc)();
} TSTRUCT;
class TCLASS{
public:
void tfunct();
const TSTRUCT t1 = { 1, &tfunct};
};

Though you didn't write a question, assuming you are facing bunch of compiler errors.
See below :
class TCLASS ; //forward declaration
struct TSTRUCT
{
unsigned int id;
void (TCLASS::*proc)( );
// // Use the TSTRUCT constructor
TSTRUCT(int i, void (TCLASS::*fptr)( ) ): id(i), proc(fptr)
{
}
} ;
class TCLASS{
public:
void tfunct();
TCLASS() : t1(1, &TCLASS::tfunct ) // initialize the const member
//~~~~~~~~~~~^ Use &TCLASS::tfunct instead of &tfunct
{
}
const TSTRUCT t1;
};

Related

Find an object stored in std::vector by comparing string to object's variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a vector that stores objects of class IdKaart.
std::vector<IdCard *> IdCard_vect;
Below the class definition:
#ifndef IDCARD_H
#define IDCARD_H
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Lock;
class IdCard {
public:
IdCard(string, string, string);
string userId();
void giveAccess(Lock*);
void removeAccess(Lock*);
bool hasAccess(Lock*);
private:
string id;
vector<Lock*> access;
string name, adress;
};
#endif // IDCARD_H
I need to be able to find an object in above vector by comparing a string with "id". Considering this id is private, member function "userId()" is used to return this string.
When above object is found, I need to be able to call the giveAccess(Lock *) function.
You can use std::find_if:
std::string idToFind = …;
auto it = std::find_if(IdCard_vect.begin(), IdCard_vect.end(),
[&](IdCard* card) { return card->userId() == idToFind; });
if (it != IdCard_vect.end()) {
// card was found, can be accessed with `*it`.
}
or a good old for-if:
IdCard* result = nullptr;
for (IdCard* card : IdCard_vect)
if (card->userId() == idToFind)
result = card;
If you can't/don't want to use lambdas, you can create a custom predicate functor:
struct pointerIdCompare : public std::unary_function<IdCard*, bool>
{
pointerIdCompare(const std::string &id) : _id(id) {}
bool operator() (const IdCard* idCard)
{ return idCard->userId() == _id; }
std::string _id;
};
And then use it in find_if to get an iterator:
std::vector<IdCard*>::const_iterator cIt = std::find_if(IdCard_vect.begin(), IdCard_vect.end(), pointerIdCompare("some-id"));
You then use this iterator to call giveAccess:
if ( cIt != IdCard_vect.end() )
{
(*cIt)->giveAccess(...);
}

How to call a function from any class by a pointer to it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm building an engine. I need to create a Timer class which will call a function by a pointer from a separate class. For example:
class MyTimer {
public:
void setTimeoutFunction( _pointer_, unsigned short timeoutMs ) {
// here we need to have a opportunity to store a _pointer_ to a function
}
void tickTimer() {
...
// here I need to call a function by a pointer
...
}
};
// Main class:
class MyAnyClass {
public:
void start() {
MyTimer myTimer;
myTimer.setTimeoutFunction( startThisFunc, 1500 ); // 1500ms = 1.5s
while ( true ) {
myTimer.tickTimer();
}
}
void startThisFunc() { ... }
}
In summation, how do you store a pointer to a function which belongs to some class and call that function by a pointer?
For your requirements, I might recommend making the timer a class template:
template <typename T>
struct MyTimer
{
using FuncPtr = void (T::*)();
MyTimer(FuncPtr ptr, T * obj, unsigned int timeout_ms)
: ptr_(ptr), obj_(obj), timeout_ms_(timeout_ms) {}
void tickTimer()
{
(obj_->*ptr_)();
}
FuncPtr ptr_;
T * obj_;
unsigned int timeout_ms_;
};
Usage:
struct MyAnyClass
{
void start()
{
MyTimer<MyAnyClass> myTimer(&MyAnyClass::startThisFunc, this, 1500);
while (true) { myTimer.tickTimer(); }
}
void startThisFunc() { /* ... */ }
};
In C++11 you can use std::function. A good guide on using it is here: http://en.cppreference.com/w/cpp/utility/functional/function
I created a new code snippet only containing the case you want.
#include <stdio.h>
#include <functional>
#include <iostream>
struct Foo {
Foo(int num) : num_(num) {}
void print_add(int i) const { std::cout << num_+i << '\n'; }
int num_;
};
int main()
{
// store a call to a member function
std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
const Foo foo(314159);
f_add_display(foo, 1);
return 0;
}

C++ - Casting a variable of {superclass} to {subclass} [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
As a practice program after learning C++, I am developing a text-based game. I am using object-oriented programming style for handling the worlds/their objects. Here's the necessary information about their definitions:
class Object
{
private:
unsigned int id;
public:
unsigned int getID() const { return id; }
};
class TakeableObject: public Object
{
...
};
class EdibleObject: public TakeableObject
{
private:
float healthEffect;
float staminaEffect;
public:
float getHealthEffect() const { return healthEffect; }
float getStaminaEffect() const { return staminaEffect; }
};
class Player
{
private:
float health;
float stamina;
TakeableObject inventory[256];
public:
eat(const EdibleObject* o)
{
health += o->getHealthEffect();
stamina += o->getStaminaEffect();
}
eat(int id)
{
if (inventory[id] == NULL)
throw "No item with that ID!";
eat((EdibleObject) inventory[id]);
inventory[id] = NULL;
}
};
So my question is - in Player::eat(int), is there a way I can make sure the Object at Player::inventory[id] is an EdibleObject (perhaps through exception handling?)
User dynamic cast to check the object type at runtime.
Or you can use a virtual function with default definition in parent and can update it as per your requirement in derived classes.
Instead of eat((EdibleObject) inventory[id]); use the following
EdibleObject *temp = dynamic_cast<EdibleObject *>( &inventory[id] );
if(temp) { eat(*temp); }
else { /* Handling */ }
Your code suffers Object splicing, make sure to get rid of that first.

How do I prototype/populating an array inside a class?(C++) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to fill an array that's a member of a class with data. Do I have to create a function that populates it, or is there a way that I can just enter the values directly?
class example
{
private:
struct exm {
int everything[3];
};
public:
exm demo;
void output();
void populate();
};
If not would this work?
void example::populate() {
demo.everything[0] = 1;
demo.everything[2] = 1;
//and so on... (could probably use a for loop)
}
Since demo is a public member you can access it directly or you can create a member function to set values.
#include <iostream>
class example
{
private:
struct exm {
int everything[3];
};
public:
exm demo;
void output();
void populate(){
demo.everything[2] = 1;
}
};
int main()
{
example Test;
Test.demo.everything[0] = 5;
Test.populate();
std::cout<< Test.demo.everything[0]; //outputs 5
std::cout<< Test.demo.everything[2]; //outputs 1
return 0;
}
`

has no member named [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
This is header file name monitor.h
class DSRAgent;
class Detector;
class ReputationSystem;
class Monitor {
public:
Monitor();
Monitor(DSRAgent* agent);
void handleTap(const Packet* packet);
void handlePublishInfo(nsaddr_t src, double identification, int count,rating* ratings);
void handlePacketSent(Packet* packet);
void publishInfo(map<nsaddr_t, rating*> ratings);
void setNetID(nsaddr_t netid);
nsaddr_t getNetID();
friend class PackTableTimer;
void setReputationSystem(ReputationSystem* rep_system);
bool isPACK(int uid);
void Terminate();
PackTableTimer* pack_table_timer;
private:
void packTableCheck();
map<nsaddr_t, double> published_ids;
PackTable pack_t;
DSRAgent* dsragent;
Detector* detector;
ReputationSystem* reputation_system;
nsaddr_t net_id;
};
class PackTableTimer : public TimerHandler {
public:
PackTableTimer(Monitor *a) : TimerHandler() { a_ = a;}
void expire(Event *e);
protected:
Monitor *a_;
};
the other file that is monitor.cc
void PackTableTimer::expire(Event *e)
{
a_->packTableCheck();
resched(PACK_TIMEOUT + PACK_TIMEOUT * Random::uniform(1.0));
}
DSRAgent* dsragent;
Monitor::Monitor(DSRAgent* agent)
{
this->dsragent = agent;
this->detector = new Detector(this);
pack_table_timer = new PackTableTimer(this);
pack_table_timer->sched(PACK_TIMEOUT + PACK_TIMEOUT * Random::uniform(1.0));
}
void Monitor::handleTap(const Packet* packet)
{
Behavior behavior;
hdr_sr *srh = hdr_sr::access(packet);
hdr_ip *iph = hdr_ip::access(packet);
hdr_cmn *cmh = hdr_cmn::access(packet);
ID cur_hop(srh->addrs()[srh->cur_addr()-1]);
nsaddr_t cur_addr = cur_hop.getNSAddr_t();
int uid = cmh->uid();
map<int, PackData*>::iterator it;
it = pack_t.find(uid);
I am getting the following errors:
**monitor.h: error: ‘PackTableTimer’ does not name a type
monitor.cc: In constructor ‘Monitor::Monitor(DSRAgent*)’
monitor.cc: error: ‘class Monitor’ has no member named ‘PackTableTimer’
monitor.cc: error: ‘pack_table_timer’ was not declared in this scope**
You need to forward-declare PackTableTimer before you can use it in monitor.h
Put this with your other forward-declarations.
class PackTableTimer;
You miss declaration of PackTableTimer class.