static public member function ( C++ ) - c++

I need to count the times my public member function creates new data in a loop.
Each time data is read it is saved into a private member varaible. Nothing is overwritten.
// my classType.h
const int ImpliedIndex = 1000;
class classType
{
private:
char privateMember[ImpliedIndex];
char privateMember2[ImpliedIndex];
public:
static void myMemberCounter;
void printMyInformation():
void mySupplier(const char[] );
...
};
//classType.cpp
int globalCounter = 0;
void classType::printMyInformation()
{
...
cout << privateMember << endl;
cout << globalCounter++ << endl;
}
void classType::mySupplier( const char buff[] )
{
strcpy( privateMember, buff );
}
// The main should clear things up a bit.
// main.cpp
int main()
{
while ( !inFile.eof() )
{
for ( int x = 0; x < 20; x++ )
{
// do file I/O here
// save each line of file into an temp array
// supply temp array with a routine defined in myClass
// re-use temp array until we run out of file
}
}
//close file
I need to change my 20 to a variable. Notice that in classType I used globalCounter to retrieve the number of types.
What I wanted to do is, globalCounter = memberCounter;
But I have to re-declare both of these varaibles, and I can't use myClass[ImpliedIndex].memberCounter with the assignment operator (=) or the binary insertion operator(<<).

This line:
static void myMemberCounter;
Should generate a compile-time error. It looks like a variable, but has type void, which doesn't make sense.
If you want a static ("class variable") counter, you should use a type like int. Then it would be easy for the class to use that counter to count the number of instances, by just incrementing the counter in the constructor. The count can be read by the outside world by adding a public class function to return it.

Related

global function and class reference

I want to send integer value in class to global function from main. How should I send it as a parameter,I am sending the parameters wrong
Tetris
{
private:
int num;
}
printBoard(Tetris &t);
int main()
{
Tetris tetris;
printBoard(board,tetris);
}
i want to send num , to printboard.
There are several problems with the shown code.
First, you're missing the class keyword when defining the class.
Second, the return type of the function is also missing.
Third, the function has only one parameter but you're passing two arguments.
i want to send num , to printboard
You can add a getter called getNum which you can use from inside your free function as shown below:
vvvvv------------->added this class keyword
class Tetris
{
private:
int num = 0; //don't forget to initialize
public:
//add a getter
int getNum() const
{
return num; //return a copy
}
};
vvvv----------------------->added return type as void
void printBoard(Tetris &t)
{
std::cout << t.getNum(); //use the getter
}
int main()
{
Tetris tetris;
printBoard(tetris);
}
Demo

(C++) Invalid value when accessing variable from another class

Whenever I try to access time_series_length from the Example class I get an invalid number.
class Indicator
{
public:
Indicator(){};
Indicator(std::vector<DayData> data, int days) // days = 30 from the main function
{
time_series = data;
time_series_length = days;
std::cout << time_series_length << std::endl; // PRINTS OUT (30) in the console
};
// Returns the length in days of the time series
int get_ts_length()
{
return time_series_length;
}
// Returns the time series in a vector of DatData structs
protected:
int time_series_length; // the length of the time_series in days
std::vector<DayData> time_series;
};
class Example : public Indicator
{
public:
Example(){};
void check()
{
std::cout << Indicator::time_series_length; // PRINTS OUT (-349926832) in the console
}
};
struct DayData
{
double adj_close;
int volume;
};
int main()
{
const int days = 30;
// ... I populate data with DayData structs
Indicator(data, days);
Example a;
a.check();
return 0;
}
I should get output
30
30
,instead I get
30
-349926832
You did not assign anyting to the created instance of the Example object a. It was only initialized. It dedicated a piece of memory to your class, but did not put anything in there, it's a random value in memory.
Initialization is missing for the Indicator class, which is part of "Example a;"
You have to call Indicator initialization with object -> a; so you call respective method -> get_ts_length() instead data member as good coding practice.

Having the same member function have different definitions for different class instances

Is it possible for the same member function to have different definitions for different objects of that class?
IMPORTANT NOTE: I cannot use a callback like in this solution. (reason explained below example)
Lets say we have this object:
struct object
{
int n;
int m;
void f();
};
Is it possible to have something like:
object a,b;
// and here to define the functions
a.f() {std::cout << n+m;}
b.f() {std::cout << n-m;}
The reason i cannot use a callback is because the function i want to define will be recursive and will overflow. What i am trying to do with this method is to create an immitation of the stack (but all the variables are stored on heap as a double chained list) and so i will call a void (void) function that has no local variables thus increasing the stack depth the function can achieve. Also important to mention is that i want to make a header file with this idea. For further context explination, this is how it should work:
MyHeader.h
template <typename PARAM_TYPE> class HEAP_FUNCTION
{
private:
struct THIS_CALL // ! THIS HAS NOTHING TO DO WITH THE __thiscall CALLING CONVENTION !
{
PARAM_TYPE* PARAM;
THIS_CALL* next_call;
THIS_CALL* prev_call;
};
THIS_CALL* FIRST_CALL;
THIS_CALL* CURRENT_CALL;
public:
HEAP_FUNCTION(PARAM_TYPE* FirstCall)
{
FIRST_CALL = new THIS_CALL;
CURRENT_CALL = FIRST_CALL;
FIRST_CALL->PARAM = *FirstCall;
}
HEAP_FUNCTION(PARAM_TYPE FirstCall)
{
FIRST_CALL = new THIS_CALL;
CURRENT_CALL = FIRST_CALL;
FIRST_CALL->PARAM = FirstCall;
}
~HEAP_FUNCTION()
{
delete FIRST_CALL;
}
void call(void);
};
Source.cpp
// This is the ilustration of the recursive method for calculating
// the 1+2+3+...+n sum.
// The "normal" definition for this function would be:
//
// unsigned long long sum(unsigned long long n)
// {
// if (n == 0) return 0;
// return n + sum(n-1);
// }
//
// The function presented bellow is the equivalent.
struct Param
{
unsigned long long n;
unsigned long long return_value;
}
int main()
{
Param start_value;
start_value.n = 10; // we will calculate 1+2+...+10
HEAP_FUNCTION<Param> Gauss(&start_value);
// We imagine this is where i define call().
// The code written in this definiton works correctly.
Gauss.call()
{
// Test if the function needs to stop further calls.
if(CURRENT_CALL->PARAM->n == 0)
{
CURRENT_CALL->PARAM->return_value = 0;
return;
}
// Prepare the parameters for the next function call.
CURRENT_CALL->next_call = new THIS_CALL;
CURRENT_cALL->next_call->PARAM = new PARAM_TYPE;
CURRENT_CALL->next_call->prev_call = CURRENT_CALL;
CURRENT_CALL->next_call->PARAM->n = CURRENT_CALL->PARAM->n - 1;
// Call the next instance of the function.
CURRENT_CALL = CURRENT_CALL->next_call;
call();
CURRENT_CALL = CURRENT_CALL->prev_call;
// Collect the return value of the callee.
CURRENT_CALL->PARAM->return_value = CURRENT_CALL->PARAM->n + CURRENT_CALL->next_call->PARAM->return_value;
// Delete the space used by the callee.
delete CURRENT_CALL->next_call;
}
// This is the actual call of the function.
Gauss.call();
// The return value is found in the start_value struct.
std::cout << start_value.return_value << std::endl;
return 0;
}
IMPORTANT NOTE: Derivering the entire class will result in a single call() definition for funtions like sum(a, b) and dif(a, b) since they will use the same PARAM struct. (Even though they are not recursive, and the probability of someone using this is very small, this method is good in a bigger program when some of your functions will have a lot of parameters and just placing them on the heap will result in more stack space)
Don't think I understood the question properly, but did you consider function overloading?

How to print out a struct pointer?

I'm trying to print out structs that I have made inside a function, and since these must be available outside of the function I have used pointers. I have declared the struct and functions like this in the header file:
struct Car{
double wheelDiam;
int numberOfWheels;
string brand;
};
void makeCars();
ostream & operator<<( ostream & out, const Car & elem );
void printCar( Car car);
The function that makes the cars looks like this:
void makeCars(){
Car *AstonMartin;
Car *Volvo;
Car *Audi;
Audi->numberOfWheels = 4;
Audi->wheelDiam = 20.0;
Audi->brand = "Audi";
Volvo->numberOfWheels = 4;
Volvo->wheelDiam = 23.0;
Volvo->brand = "Volvo";
AstonMartin->numberOfWheels = 5;
AstonMartin->wheelDiam = 25.0;
AstonMartin->brand = "Aston Martin";
}
and I have made another function that prints out the struct (overloaded operator=):
ostream & operator<<( ostream & out, const Car & elem ){
out << elem.brand<<" "<<elem.numberOfWheels <<" "<<elem.wheelDiam<<endl;
return out;
}
void printCar( Car car){
cout << car << endl;
}
but when I call the functions in main() it doesn't print anything and I get an error message:
int main(){
makeCars();
printCar(*AstonMartin);
return 0
}
whats the correct way to do this?
first of all, you declare the variable Car * AstonMartin in a function. This variable actually exists ONLY in the makeCars function.
you can't use your object or even delete it
a better way to do is
void setCarAttributes(Car *c)
{
// set everything for you car
c->setBrand("Aston Martin");
// etc ...
}
void printCar()
{
// print what you want
  }
int main()
{
Car *AstonMartin = new Car();
setCarAttributes(AstonMartin);
printCar(AstomMartin);
}
nevermind the variable you declare in your functions can't be used in other functions. To use a variable everywhere you need to declare a global variable but in this case it's not necessary just declare a Car * and give it as parameter to your functions

initialize a static member with a file

I have a dictionary class , for spell checking . I have an array as the list of words , and I must initialize it with a file that there are words in it .
my problem is that , I need my wordlist variable to be a static variable , cause only one of it is enough for any other extra object created from the dictionary class and it is logical , however there is no need for a second object of the class , but what if we needed more than one object? is there a way?
#ifndef DICTIONARY_H
#define DICTIONARY_H
class Dictionary
{
public:
static const int SIZE = 109582;
Dictionary();
bool lookUp(const char *)const;
private:
void suggestion(const char *)const;
char *wordList[SIZE];
};
#endif
wordlist must be static ...
I only can think of this kind of defining ...
Dictionary::Dictionary()
{
ifstream inputFile("wordsEn.txt", std::ios::in);
if (!inputFile)
{
cerr << "File could not be opened." << endl;
throw;
}
for (int i = 0; i < SIZE && !inputFile.eof(); ++i)
{
wordList[i] = new char[32];
inputFile >> wordList[i];
}
}
There are many ways to solve the programming problem.
Here's my suggestion:
Move the static members out of the class.
class Dictionary
{
public:
Dictionary();
bool lookUp(const char *)const;
private:
void suggestion(const char *)const;
};
In the .cpp file, use:
static const int SIZE = 109582;
static std::vector<std::string> wordList(SIZE);
static int initializeWordList(std::string const& filename)
{
// Do the needul to initialize the wordList.
}
Dictionary::Dictionary()
{
static int init = initializeWordList("wordsEn.txt");
}
This will make sure that the word list is initialized only once, regardless of how may instances of Dictionary you create.