I tried using a static func in class A.
class A {
private:
static int a, b;
static void init(void) {
a = 1, b=0;
}
};
class B {
private:
A::init();
}
It is giving non-friend class cannot have a qualified name.
The following works:
class A {
private:
static int a;
public:
static void initialize();
void addStatic();
void getA();
};
class B {
public:
void initializeClassA();
};
int A::a = 10;
void A::addStatic() {
++a;
}
void A::getA() {
return a;
}
void A::initialize() {
a = 0;
}
void B::initializeClassA() {
A::initialize();
}
int main() {
A a;
B b;
std::cout << "Before Adding - " << a.getA() << std::endl;
for(int i = 0; i < 3; ++i)
{
a.addStatiic();
}
std::cout << "After Adding - " << a.getA() << std::endl;
b.initializeClassA();
std::cout << "After Reinitializing - " << a.getA() >> std::endl;
return 0;
}
Related
I've got a class that needs to become a singleton. All good and fine only that it has a non-default constructor, i.e. it takes three arguments.
The best I could come up with is, to set the constuctor private and then provide some kind of public "setup" function.
Are there any better solutions? My work around so far looks something like - any ideas to improve this are welcome!
#include <iostream>
class singltn {
private:
static singltn *instance;
int data;
// Private constructor so that no objects can be created.
singltn() {
data = 0;
}
int _AA;
int _BB;
int _CC;
public:
static singltn *getInstance() {
if (!instance)
instance = new singltn;
return instance;
}
void setup(int AA, int BB, int CC) {
_AA = AA;
_BB = BB;
_CC = CC;
}
int getData() {
return this->data;
}
void setData(int data) {
this -> data = data;
}
int getAA(){
return this->_AA;
}
};
//Initialize pointer to zero so that it can be initialized in first call to getInstance
singltn *singltn::instance = 0;
int main(){
singltn *a = a->getInstance();
a->setup(111,222,333);
std::cout << "dat " << a->getData() << " _AA " << a-> getAA() << std::endl;
a->setData(100);
std::cout << "dat " << a->getData() << " _AA " << a-> getAA() << std::endl;
singltn *b = b->getInstance();
std::cout << "dat " << b->getData() << " _AA " << a-> getAA() << std::endl;
return 0;
}
You can use a static factory/getter function that calls a private constructor. Something like this:
class Foo {
public:
static Foo& GetInstance() {
static Foo foo(param1, param2);
return foo;
}
private:
Foo(int a, int b) {
// ...
}
}
Of course, that requires your factory function to somehow know the parameters somehow.
Don't use real singleton (which handles creation + unique instance + global access), and adapt it:
class MyClass
{
private:
int data = 0;
int _AA;
int _BB;
int _CC;
static std::unique_ptr<MyClass> uniqueInstance;
MyClass(int AA, int BB, int CC) : _AA(AA), _BB(BB), _CC(CC) {}
MyClass(const MyClass&) = delete;
MyClass& operator =(const MyClass&) = delete;
public:
static void Create(int AA, int BB, int CC)
{
// if (uniqueInstance) throw std::runtime_error("Call it only once");
uniqueInstance = std::make_unique<MyClass>(AA, BB, CC);
}
static MyClass& GetInstance()
{
if (!uniqueInstance) throw std::runtime_error("Call Create before");
return *uniqueInstance;
}
int getData() const { return this->data; }
void setData(int data) { this->data = data; }
int getAA() const { return _AA; }
};
std::unique_ptr<MyClass> MyClass::uniqueInstance;
int main(){
MyClass::Create(111, 222, 333);
auto& a = MyClass::GetInstance();
std::cout << "dat " << a.getData() << " _AA " << a.getAA() << std::endl;
a.setData(100);
std::cout << "dat " << a.getData() << " _AA " << a.getAA() << std::endl;
}
Adapting Steve's Answer to provide a setup function for the singleton class:
class Foo {
public:
static Foo& GetInstance() { return SetupInstance(-1, -1); }
static Foo& SetupInstance(int a, int b) {
static Foo foo(a, b);
return foo;
}
private:
Foo(int a, int b) {
// ...
}
};
As the constructor of the static singleton get's only called once, multiple calls to SetupInstance will not re-create a new object of Foo, but always return the object which was created at the first call.
I have an Abstract Class operations that inherits from VAR Class , which then all the operations derived class(out,sleep,Add) inherit from the operations class. FSM Class inherits from Var also, so That I want one instance of VAR class inside my program.
I am trying to make vector < pair< string, int>> var as a shared data between the FSM class and the Operations class and its deviates . I initialized the var in the main through the FSM class .
Each time we call the exist function in VAR through Class operation , it returns it doesn't exits cause it is empty ! How can I overcome this?
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class VAR
{
public:
vector<pair<string, int>> var;
VAR()
{
cout << "created VAR" << endl;
}
~VAR(){ cout << "Destrioed VAR" << endl; }
void createVar(string x,int y)
{
pair<string, int>t;
t.first = x;
t.second = y;
var.push_back(t);
}
int getVarValue(string x)
{
for (int i = 0; i<var.size(); i++)
{
if (var[i].first == x)
{
return var[i].second;
}
}
}
void setVarValue(string& x, int y)
{
for (int i = 0; i<var.size(); i++)
{
if (var[i].first == x)
{
var[i].second = y;
i = var.size();
}
}
}
bool exits(string& name)
{
for (int i = 0; i<var.size(); i++)
{
if (var[i].first == name)
return true;
}
return false;
}
};
class operations : virtual public VAR
{
public:
operations()
{
cout << "operations created" << endl;
}
~operations()
{
cout << "operations Destroied" << endl;
}
void virtual excute() = 0;
};
class Out :public virtual operations
{
public:
string s;
Out(string xx = "") :s(xx)
{
cout << "Out created" << endl;
}
~Out()
{
cout << "Out Destroied" << endl;
}
void virtual excute()
{
cout << "out Class" << endl;
if (exits(s))
cout<<"it never reach here, WHY !"<<endl;
}
};
class Add :public virtual operations
{
public:
string s;
Add(string ss = "") :s(ss)
{
cout << "ADD created" << endl;
}
~Add()
{
cout << "Add Destroied" << endl;
}
void virtual excute()
{
string ex1 = s.substr(s.find('=') + 1, s.find('+')), ex2 = s.substr(s.find('+') + 1);
if (exits(ex1))
cout<<"it never reach here, WHY !"<<endl;
else
result = atoi(ex1.c_str());
if (exits(ex2))
cout<<"it never reach here, WHY !"<<endl;
}
};
class state
{
public:
vector<operations*> instructionList;
string name;
void exec_all()
{
for (int x = 0; x < instructionList.size(); x++)
instructionList[x]->excute();
}
};
class transition
{
public:
vector < pair<state, vector<pair<state, int>>>> trans;
static int currentState;
};
class FSM :public virtual VAR, public virtual transition
{
public:
FSM()
{
cout << "FSM" << endl;
}
void intialize()
{
createVar("X", 1);
createVar("Y", 5);
}
};
void main()
{
FSM x;
pair<state, vector<pair<state, int>>> p1;
pair<state, int>p2;
x.intialize();
p2.first.name = "b";
p2.second = 3;
p1.first.name = "a";
p1.second.push_back(p2);
x.trans.push_back(p1);
x.trans[0].first.instructionList.push_back(new Add("X=X+Y"));
x.trans[0].first.instructionList.push_back(new Out("X"));
x.trans[0].first.exec_all();//wrong output cause exist() returns false
}
A minimal complete example looks something like this:
#include <iostream>
using namespace std;
class VAR
{
public:
int var;
virtual ~VAR()
{}
void setVar(int n)
{var=n;}
};
class Out :public VAR
{};
class FSM :public VAR
{};
int main()
{
FSM x;
x.setVar(5);
Out OP;
if (x.var==OP.var)
cout<<"it reaches here now" << endl;
else
cout << "it fails" << endl;
return(0);
}
And one way to fix it is like this:
class VAR
{
public:
static int var;
int var;
virtual ~VAR()
{}
void setVar(int n)
{var=n;}
};
int VAR::var=0;
I want to define a container in the base class, which contains function obj or anything that can make my purpose happen. These function obj can call derived classes' functions. they all take same parameters.
#include <vector>
#include <functional>
#include <iostream>
class Foo {
Foo() {}
virtual ~Foo(){}
virtual void init()
{ registerCallback(0, &Foo::print_ori ); }
void print_ori(int i) const { std::cout << i << '\n'; }
void registerCallback(int key, ??? cb ) // NOT SURE HOW TO DEFINE THIS
{
callbacks[key] = cb;
}
void runCallbacks(int key, int n)
{
auto i = callbacks.find(key);
if (i != callbacks.end()) {
(*i)(*this, n);
}
}
std::map<int, std::function<void(const Foo&, int) > > callbacks; // obviously, it's wrong. how to fix it?
};
struct Foo2 : public Foo {
Foo2(int num) : Foo(num) {}
virtual void init()
{
Foo::init();
registerCallback(11, &Foo2::print1 );
registerCallback(12, &Foo2::print2 );
}
void print1(int i) const { std::cout << " - Foo2.p1 - " << i << endl; }
void print2(int i) const { std::cout << " - Foo2.p2 - " << i << endl; }
};
int main()
{
Foo* obj = new Foo2();
obj->init();
obj->runCallbacks(12, 456);
}
Here's a way to achieve what your code looks like it's trying to do, without using function pointers:
class Foo {
Foo() {}
virtual ~Foo(){}
void print_ori(int i) const { std::cout << i << '\n'; }
virtual void do_runCallbacks(int v)
{
}
void runCallbacks()
{
print_ori(3)
do_runCallBacks(3);
}
};
struct Foo2 : public Foo {
Foo2(int num) : Foo(num) {}
void do_runcallbacks(int v)
{
print1(v);
print2(v);
}
void print1(int i) const { std::cout << " - Foo2.p1 - " << i << endl; }
void print2(int i) const { std::cout << " - Foo2.p2 - " << i << endl; }
};
int main()
{
Foo* obj = new Foo2();
obj->runCallbacks();
}
Now, there may well be reasons to do this completely differently, but I don't see why you should need both virtual functions and inheritance, AND function objects/function pointers. That seems quite wrong to me ("smells bad")
Edit:
Here's something I came up with, that solves the type of problem you describe after edits of the original question.
#include <iostream>
#include <map>
using namespace std;
class event_interface
{
public:
virtual void action(int n) = 0;
};
class event_manager
{
public:
event_manager(int n) : num(n) {}
void register_event(int key, event_interface *eh)
{
handlers[key] = eh;
}
void callback(int key)
{
auto h = handlers.find(key);
if (h != handlers.end())
{
h->second->action(num);
}
}
private:
map<int, event_interface *> handlers;
int num;
};
class handler1 : public event_interface
{
public:
void action(int n) { cout << "in handler1::action. n=" << n << endl; }
};
class handler2 : public event_interface
{
public:
handler2(int n) : data(n) {}
void action(int n)
{
cout << "in handler2::action. n=" << n
<< " data = " << data << endl;
}
private:
int data;
};
class multihandler
{
private:
class handler3: public event_interface
{
public:
void action(int n) { cout << "in handler3::action. n=" << n << endl; }
};
class handler4: public event_interface
{
public:
handler4(multihandler *m) : mh(m) {}
void action(int n)
{
cout << "in handler4::action. n=" << n
<< " data = " << mh->data << endl;
}
private:
multihandler* mh;
};
public:
multihandler(event_manager& em) : h4(this)
{
em.register_event(62, &h3);
em.register_event(63, &h4);
data = 42;
}
private:
handler3 h3;
handler4 h4;
int data;
};
int main()
{
event_manager mgr(3);
handler1 h1;
handler2 h2(77);
multihandler mh(mgr);
mgr.register_event(12, &h1);
mgr.register_event(13, &h2);
int evts[] = { 12, 63, 62, 13, 18 };
for(auto i : evts)
{
cout << "Event: " << i << endl;
mgr.callback(i);
}
}
how to count the number of objects created in c++
pls explain with a simple example
Create template class with a static counter.
Each object in your application would then extend this template class.
When constructor is called increment static count (static variable is per class - shared by all objects of that class).
For example see Object Counter using Curiously recurring template pattern:
template <typename T>
struct counter
{
counter()
{
objects_created++;
objects_alive++;
}
counter(const counter&)
{
objects_created++;
objects_alive++;
}
protected:
virtual ~counter()
{
--objects_alive;
}
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
// ...
};
class Y : counter<Y>
{
// ...
};
Usage for completeness:
int main()
{
X x1;
{
X x2;
X x3;
X x4;
X x5;
Y y1;
Y y2;
} // objects gone
Y y3;
cout << "created: "
<< " X:" << counter<X>::objects_created
<< " Y:" << counter<Y>::objects_created //well done
<< endl;
cout << "alive: "
<< " X:" << counter<X>::objects_alive
<< " Y:" << counter<Y>::objects_alive
<< endl;
}
Output:
created: X:5 Y:3
alive: X:1 Y:1
template <class T>
class Counter
{
private:
static int count;
public:
Counter()
{
count++;
}
Counter(const Counter &c)
{
count++;
}
~Counter()
{
count--;
}
static int GetCount() {
return count;
}
}
template<class T>
int Counter<T>::count = 0;
class MyClass : private Counter<MyClass>
{
public:
using Counter<MyClass>::GetCount;
}
This technique is called CRTP
Number of objects for what? If you want to count the number of objects of a specific class, you can use a static counter. Something like below.. Increment counter on creation and decrement while destruction..
class A
{
public:
static int counter;
A()
{
counter ++;
}
virtual ~A()
{
counter --;
}
};
int A :: counter = 0;
You have to overload the new and delete operators
to count memory allocations.
void * operator new (size_t size)
{
void * p = malloc (size);
num_allocations++;
return p;
}
void operator delete (void * p)
{
num_deletions++;
free (p);
}
You could create a counter variable into the public: of your class (assuming here you're talking about counting objects from a class you created)
class Widget {
public:
Widget() { ++count; }
Widget(const Widget&) { ++count; }
~Widget() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
// obligatory definition of count. This
// goes in an implementation file
size_t Widget::count = 0;
Taken from ddj.com
update on code as opposed to "stefanB" solution, some variables are in protected access mode and will not be accessible.
template <typename T>
struct counter
{
counter()
{
std::cout << "object created"<< endl;
this->objects_created++;
this->objects_alive++;
}
counter(const counter& test)
{
std::cout << "object created:" << test << endl;
this->objects_created++;
this->objects_alive++;
}
static int getObjectsAlive(){
return objects_alive;
}
static int getObjectsCreated(){
return objects_created;
}
protected:
virtual ~counter()
{
std::cout << "object destroyed"<< endl;
--objects_alive;
}
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
// ...
};
class Y : counter<Y>
{
// ...
};
Usage for completeness:
int main()
{
X x1;
{
X x2;
X x3;
X x4;
X x5;
Y y1;
Y y2;
} // objects gone
Y y3;
cout << "created: "
<< " X:" << counter<X>::getObjectsCreated()
<< " Y:" << counter<Y>::getObjectsCreated() //well done
<< endl;
cout << "alive: "
<< " X:" << counter<X>::getObjectsAlive()
<< " Y:" << counter<Y>::getObjectsAlive()
<< endl;
}
class Foo {
public:
Foo() { do_something = &Foo::func_x; }
int (Foo::*do_something)(int); // function pointer to class member function
void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; }
private:
int func_x(int m) { return m *= 5; }
int func_y(int n) { return n *= 6; }
};
int
main()
{
Foo f;
f.setFunc(false);
return (f.*do_something)(5); // <- Not ok. Compile error.
}
How can I get this to work?
class A{
public:
typedef int (A::*method)();
method p;
A(){
p = &A::foo;
(this->*p)(); // <- trick 1, inner call
}
int foo(){
printf("foo\n");
return 0;
}
};
void main()
{
A a;
(a.*a.p)(); // <- trick 2, outer call
}
The line you want is
return (f.*f.do_something)(5);
(That compiles -- I've tried it)
"*f.do_something" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f." prefix.
class A {
int var;
int var2;
public:
void setVar(int v);
int getVar();
void setVar2(int v);
int getVar2();
typedef int (A::*_fVar)();
_fVar fvar;
void setFvar(_fVar afvar) { fvar = afvar; }
void insideCall() { (this->*fvar)(); }
};
void A::setVar(int v)
{
var = v;
}
int A::getVar()
{
std::cout << "A::getVar() is called. var = " << var << std::endl;
return var;
}
void A::setVar2(int v2)
{
var2 = v2;
}
int A::getVar2()
{
std::cout << "A::getVar2() is called. var2 = " << var2 << std::endl;
return var2;
}
int main()
{
A a;
a.setVar(3);
a.setVar2(5);
// a.fvar = &A::getVar;
a.setFvar(&A::getVar);
(a.*a.fvar)();
a.setFvar(&A::getVar2);
(a.*a.fvar)();
a.setFvar(&A::getVar);
a.insideCall();
a.setFvar(&A::getVar2);
a.insideCall();
return 0;
}
I extended Nick Dandoulakis's answer. Thank you.
I added a function which set the member function pointer from outside of the class. I added another function which can be called from outside to show inner call of member function pointer.
Try (f.*do_something)(5);
#include<iostream>
using namespace std;
class A {
public:
void hello()
{
cout << "hello" << endl;
};
int x = 0;
};
void main(void)
{
//pointer
A * a = new A;
void(A::*pfun)() = &A::hello;
int A::*v1 = &A::x;
(a->*pfun)();
a->*v1 = 100;
cout << a->*v1 << endl << endl;
//-----------------------------
A b;
void(A::*fun)() = &A::hello;
int A::*v2 = &A::x;
(b.*fun)();
b.*v2 = 200;
cout << b.*v2 << endl;
}
I think calling a non static member of the class could also be done using a static member function.