I want to create an array in class hash and use it in its methods. I tried declaring it in public but still other methods are not able to access it.
Here is my class declaration:
class hash
{
public:
string hash_table[size]; //size is global variable;
void initialize(int,string*,int); //I pass `hash_table` pointer and two other `int` type //arguments.
int hash_function(string, int);
void quad_prob(int, int, string* , string); //`hash_table` array is used in this method also.
void print(string*); //to print `hash_table` array
};
I have to use array only.
Also, can pleas explain when I use hash h; in int main(), what happens?
Here is complete code (without using class structure) : http://codepad.org/DQggdoI6
It looks like you are trying to convert existing code to a class, yes? Keep your string hash_table[] private in the class. Then remove that parameter from each of the functions on codepad. So initialize, as folks have pointed out, becomes the constructor hash(int n, int size) and initializes hash_table (hash_table = new string[size] or some such). Similarly, print becomes just plain print(), and can refer directly to hash_table since it's a member function of the hash class.
your array will be initialized when you create a new hash object. You would use hash h before any code using the object. When you make a new object, your constructor sets up your object for later use in your code. From there you should be able to use your code from your class.
first I would suggest you use a vector.
Secondly once its defined in your class you just access it by name.
class foo
{
public:
foo(): vecfoo(5)
{}
void DoSomeThing()
{
for_each(begin(vecfoo),end(vecfoo),[](const string &){...});
}
private:
vector<string> vecfoo;
};
Related
I'm trying to create a custom vector class and overloading all operators. consider the following code:
template <class T>
class vector{
private:
T * arrayOfObj;
// other class members
public:
Vector(){
arrayOfObj = new T[100];
}
vector(int size);
// other functions for vector class, overloaded [], =, etc.
}
in another class, I need to return the vector but with a pointer like when we return an array:
#include "B.h"
class c {
vector<B> vect;
public:
B * getArray(){
return vect;
}
First, is it possible to retrun a vector like an array?
Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?
First, is it possible to retrun a vector like an array?
Sure, that's what std::vector::data() does. It's as simple as doing return arrayOfObj; in whatever method or operator overload.
Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?
Not possible. Either you allow access to your internal storage via a public function or you don't allow that, your choice. In c::getArray() you could also copy all elements of vect into a new array - this way noone will alter vect from the outside and you don't have to provide access to internal storage of vector class.
There is also friend mechanism that allows one function or class to access private members of another class, but it's usually worse than public access.
I'd like to create a class with a statically declared array. I'd like to extend the class that basically changes the size of the array in the derived class. Everything else would stay the same.
namespace someNameSpace {
const uint8_t STATIC_ARRAY_SIZE = 50; // <-- change this value in a derived class?
class BaseClass {
private:
int some_array[STATIC_ARRAY_SIZE];
public:
void some_function_that_uses_above_array(){ ... };
}
}
Is there a way to do this without using templating? (I need the arrays to be allocated memory at compile time).
You can use template meta-programming for this:
namespace someNameSpace {
template <size_t STATIC_ARRAY_SIZE>
class BaseClass {
private:
int some_array[STATIC_ARRAY_SIZE];
public:
void some_function_that_uses_above_array(){ ... };
}
class Derived : public BaseClass<42> {
...
}
}
If you want to allocated at compile time, it is mean not dinamically allocated i think the solution you want still is template. At compile time for each different template parameter the compiler will generate a copy of class.
Example:
With #sturcotte06 code, if you declare in someplace BaseClass<10> or BaseClass<20>, for each parameter 10 and 20, the compiler will copy the code of class and apply the parameter like a #define.
In this link search for "PrintTwice function with int and double", there is a pratical example.
If you can't use template because of restrictions, i don't recommend but you can pass the array through constructor as a smart pointer, to avoid null reference is important check pointer on costructor and take a care on destructor.
I am having difficulty getting my head around how to pass a class member function to a subclass (not derived).
My top level class is like this:
class CTop
{
public:
CTop();
int func1(void);
private:
CFnList* _funcList;
};
CTop::CTop():
_funcList(0)
{
_funcList = new CFnList();
_funcList->addFnPtrToList(0, &CTop::func1);
}
int CTop::func1(void)
{
// Does some stuff...
}
My function list class is like this:
class CFnList
{
public:
// Public functions
CFnList();
void addFnPtrToList(int index, int (*fn)(void));
private:
// Fn pointer list
typedef struct
{
int index;
int (*fn) (void);
}fn_list_t;
// function pointer list
QVector<fn_list_t> _fn_list;
};
So basically here I have an instance of class CTop and one of its members is a pointer to a class CFnList. CFnList pointer is instantiated in the constructor of CTop. Then I want to pass in a pointer to one of CTop's member functions to CFnList by calling the following line:
"_funcList->addFnPtrToList(0, &CTop::func1);"
I get issue (quite rightly) that addFnPtrToList does not take the parameters (int, (CTop::*)()). So the compiler knows this function is a certain member function and not just a generic (maybe static) function.
Is there a way to pass the a pointer to the member function into the sub-class? In my case I want the sub-class to be able to call this function. I am thinking I probably have to make static member functions or something, but the syntax is eluding me on how to do this.
All help / advise appreciated.
Fodder
CTop::func1 is a member function. &CTop::func1 is NOT a function pointer, it is a pointer to member (function). Those can not be mixed either in storing or calling. it is not compatible with int (*fn)(void), as the latter takes no arguments and the former requires an object that is passed as the hidden this.
For these reasons you can't have a simple but uniform facility. You either can go with simple function pointers, or pairs of PTM+object pointer, or use wrappers -- handmade or stock like boost::function fueled by boost::bind. If you have C++11 or TR1 you can use the std:: equivalents of the latter.
A declaration in the form:
int (*fn)(void)
cannot point to a member function. It can only point to a free function. Philispophically, this is because the calling conventions for member functions are different then that for free functions. Consider for example the need for a this pointer in the context of a member function call.
The syntax for declaring a pointer-to-member-function is like this:
int (CTop::*fn)(void)
There is an entire section in the C++ FAQ dedicated to member function pointers. Check it out.
You are passing the member function as if it were a regular function. That fails to include the 'this' reference to the class. In order to pass member functions, you have to be able to re-reference it from the original 'this'. Take a look at the following, instead.
typedef void (CTop::*OBJFNC)(args);
_funcList = new CFnList();
_funcList->addFnPtrToList(0, this, &CTop::func1);
void addFnPtrToList(int index, CTop* pobj, OBJFNC pfnc)
{ ... Store both ...
}
Now elsewhere you can execute it with the following.
(pobj->*pfnc)(args);
Here is the final solution, it uses a mixture of passing the instance of the object CTop and usage of template class for CFnList:
My top level class is like this (more or less the same except for the declaration of _funcList to includes the class type and to pass in the "this" to the constructor:
class CTop
{
public:
CTop();
int func1(void);
private:
CFnList<CTop>* _funcList;
};
CTop::CTop():
_funcList(0)
{
_funcList = new CFnList(this);
_funcList->addFnPtrToList(0, &CTop::func1);
}
int CTop::func1(void)
{
// Does some stuff...
}
My function list class is like this:
template<class T>
class CFnList
{
public:
// Public functions
CFnList(T *parent);
void addFnPtrToList(int index, int (T::*fn)(void));
private:
// Pointer to the parent (or owner is perhaps more correct)
T* _parent;
// Fn pointer list
typedef struct
{
int index;
int (T::*fn) (void);
}fn_list_t;
// function pointer list
QVector<fn_list_t> _fn_list;
};
// Constructor
template <class T>
CFnList<T>::CFnList(T *parent) :
_parent(parent),
_fn_list(0)
{
}
// addFnPtrToList:
template <class T>
void CFnList<T>::addFnPtrToList(int index, int (T::*fn)(void))
{
_fn_list.append((fn_list_t){index, fn});
}
So the major changes are:
1. Pass the CTop type in by using changing CFnList into a template.
2. Pass in the instance of the object CTop (so that the pointer to the function can be called) by passing "this" into the constructor and then template class stores it as a pointer to the given template type.... vio-la!...easy :o
Thanks to all who contributed :))
class OSwitch {
private:
Operator *operators[];
//int variable; <-- unused variable
public:
OSwitch() {}
~OSwitch() {}
void setOperator(int id, Operator *op) {
operators[id] = op;
}
void execute(int id) {
operators[id]->execute();
}
};
There are several subclasses of the abstract baseclass Operator.
When calling setOperator() for more than one time, the array "forgets" the last element.
for example
XOperator a;
YOperator b;
os.setOperator(1,a);
os.setOperator(2,b);
os.execute(1); // <- wont work
But when the int variable (or any other variable in OperatorSwitch) is declared, it works.
I dont have any idea how this works.
Thanks for any hint.
Your member variable operators is an unsized array, which is an incomplete type and not allowed in a class definition.
What you probably want instead is a map of integers to pointers:
#include <map>
class OSwitch
{
private:
std::map<int, Operator *> operators;
public:
void setOperator(int id, Operator *op) { operators[id] = op; }
void execute(int id) { operators[id]->execute(); }
};
Note that it will be an error to call execute on an ID that has not been assigned a valid pointer. You can make this more robust by checking for existence of the map element first.
Array operators doesn't have a size declared. Either declare the number of elements in the array, as in operators[10], or use std::vector instead.
You need to initialize the array before adding data.
I would recommend you to work with values, not pointers, in this array, because then you won't have problems defining who will delete the Operator*s afterwards (i.e. the caller of setOperator or ~OSwitch()).
1.
I know that it is possible to initialise an array of structures in the declaration. For example:
struct BusStruct
{
string registration_number;
string route;
};
struct BusStruct BusDepot[] =
{
{ "ED3280", "70" },
{ "ED3536", "73" },
{ "FP6583", "74A" },
};
If the structure is changed into a class, like this:
class BusClass
{
protected:
string m_registration_number;
string m_route;
public:
// maybe some public functions to help initialisation
};
Is it possible to do the same as for the structure (i.e. declare and initialise an array of classes at the same time)?
2.
Am I correct to think that it is not possible to declare and initialise vector<BusStruct> or vector<BusClass> at the same time?
Is it possible to do the same as for the structure (i.e. declare and initialise an array of classes at the same time)?
Not unless you create a suitable constructor:
class BusClass
{
protected:
string m_registration_number;
string m_route;
public:
// maybe some public functions to help initialisation
// Indeed:
BusClass(string const& registration_number,
string const& route)
:m_registration_number(registration_number),
m_route(route) { }
};
Or you make all members public and omit the constructor, in which case you can use the same initialization syntax as for the struct. But i think that's not what you intended.
Am I correct to think that it is not possible to declare and initialise vector<BusStruct> or vector<BusClass> at the same time?
No it's not possible with current C++. You can however use libraries that make this possible. I recommend Boost.Assign for that. For that, however, your class has to have a constructor, and likewise your struct too - Or you need to create some kind of factory function
BusStruct make_bus(string const& registration_number,
string const& route) { ... }
If you want to keep the struct initializable with the brace enclosed initializer list in other cases.
No, you would not be able to initialize classes the way you can with structures. But you can write the class constructor inside the array declaration.
C++ has no built in way of initializing vectors, unless you want to load the vector from an array that you have initialized.
C++ natively supports two forms of vector initialization and neither is what you are looking for.
1: Every element the same as in:
vector<int> ints(4,1000); //creates a vector of 4 ints, each value is 1000.
2: Copy from an existing vector as in:
vector<int> original(3,1000); //original vector has 3 values, all equal 1000.
vector<int> otherVector(original.begin(),original.end()); //otherVector has 3 values, copied from original vector