Unused Variable prohibits print? - c++

I am not sure why my function is not working. It should be printing out something out (an error message after the user goes out of bounds)I have set the array index at 3 index slots. I'm also getting an error "unused variable 'yourArray' I am not sure where to go from here. Still trying to learn c++ so and advice or help will be greatly appreciated.
#include <iostream>
using namespace std;
class safeArray{
public:
void outofBounds(int,int);
int yourArray[3];
int i;
};
void outofBounds(int,int);
int yourArray[3];
int i;
void outofBounds(int yourArray[],int sizeofArray) {
for (i=0;i<sizeofArray;i++){
cout<<"Please enter integer";
cin >>yourArray[i];
yourArray[i]++;
for (i=0;i>sizeofArray;){
cout<<"safeArray yourArray (" <<yourArray[0]<<","<<yourArray[3]<<")"
<<endl;
}}}
int main() {
void outofBounds(int,int);
int yourArray[3]; //Error: Used variable "yourArray"
};

Your Program is running fine. Unless you added the "-Werror" flag to the compiler, which would treat the "unused variable"-Warning as an Error.
The code compiles fine as seen on here: http://coliru.stacked-crooked.com/a/d648b94f205b51dc
Though your Program does not do what you want it to do, because of the following reasons:
1.) You have 3 redefinitions of outofBounds inside different namespaces:
one inside the classes namespace SafeArray which is a member function
of it
then inside the global space
and then inside the main-function (the entry point)
But the one being actually defined is the one in the global space (2nd one)
2.) You are not passing anything to the function inside main.
define your Array there first then call the function by doing:
int yourArray[3];
outofBounds(yourArray, 3);
3.) You probably wanted to define the member method "outofBounds" inside SafeArray-class. This can be done by writing the scope operator:: which specifies the class to which the member function belongs to:
class SafeArray { // is a class, can also be struct since everything is public anyways
public:
void outofBounds(int,int); // a member of the class SafeArray
// private:
int yourArray[3];
int i;
};
void SafeArray::outofBounds(int yourArray[],int sizeofArray) {
// do something...
}
but then again you need some constructor that initializes the members of your class. Some work needs to be done to make it work, like you want. Good Luck :)

Related

Get call identifier or address of a function

Suppose that I have this code:
class MyClass
{
public:
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
};
MyClass myClassObject;
int main()
{
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
How can I know inside function what number of call is it?
Note that I will probably have 100 function calls placed in code. Also this should work in Visual Studio on Windows and Clang on Mac.
I had one workaround:
void SomeFunction(const char* indetifier = "address")
{
CheckAddress(indetifier); // This will check if address is stored. If it is not, create variables, if it is, if addresses matches use variables that are tied to that address.
}
I tried not to assign a new string to an "indetifier" and to let it to use default string ("address"). This of course didn't worked well as compiler will optimize "indetifier", so I was thinking that maybe a solution would be to disable optimizations for that variable, but I didn't because there should be some more elegant solution.
Also one thing came on my mind, maybe I could force inline a function and then get it's address, but this also seams like bad workaround.
I could also create new classes for every call but I would like to avoid this as there will be a lot of function calls and I don't want to think 100 different names.
If there is a way to create class object only at first call this would be awesome.
I hope that you understand what I want, sorry if something is not that clear as I am beginner coder.. :D
EDIT:
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
If the first call is to be tracked per object, then you need a member variable that keeps track of how many times SomeFuntion has been called for that object.
If the first call is to be tracked independent of objects, then you can use a static function variable that keeps track of how many times SomeFuntion has been called for that object.
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
So make a non-static counter?
class MyClass {
int count;
public:
MyClass () : count(0) { }
void SomeFunction () {
++ count;
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
Or just pass it as a parameter...
class MyClass {
public:
void SomeFunction (int count) {
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(1); // First call
myClassObject.SomeFunction(2); // Second call
myClassObject.SomeFunction(3); // Third call
}
But I'm really wondering what you're actually trying to do, and I highly suggest sitting back and rethinking this whole thing, because there are a number of red flags / confusing points here...
If you're only interested in checking whether it's the first call, you can add a bool SomeFunction_first_call; to the MyClass, to act as a flag. The constructor sets the bool to true. MyClass::SomeFunction() uses the conditional check if (SomeFunction_first_call) /* ... */ to determine whether it's the first call, as follows:
class MyClass
{
bool SomeFunction_first_call;
public:
MyClass() : SomeFunction_first_call(true) {}
void SomeFunction()
{
if (SomeFunction_first_call)
{
// This code only executes on first call.
do_something();
// Successfully handled first call, set flag to false.
SomeFunction_first_call = false;
}
// This code always executes.
do_something();
}
};
Similarly, if you're only concerned about the first HOWEVER_MANY_CALLS calls, where HOWEVER_MANY_CALLS is a number, you can use something like this:
#include <cstdint>
class MyClass
{
uint8_t SomeFunction_calls;
public:
MyClass() : SomeFunction_calls(0) {}
void SomeFunction()
{
// This segment will be executed until (SomeFunction_calls == HOWEVER_MANY_CALLS).
// After this, the segment will be skipped, and the counter will no longer increment.
if (SomeFunction_calls < HOWEVER_MANY_CALLS)
{
// This code only executes on first HOWEVER_MANY_CALLS calls.
do_something();
// Increment counter.
++SomeFunction_calls;
}
// This code always executes.
do_something();
}
};
Make sure to use the appropriately signed variable for the number of calls that need special handling (i.e. uint8_t for 0..255, uint16_t for 256..65,535, etc.). If different instances of MyClass will need to keep track of a different number of calls, then use a non-type template parameter to indicate this, and optionally, a defaulted typename to indicate what type the counter should be.
#include <cstdint>
template<uint64_t N, typename T = uint64_t>
class MyClass {
T SomeFunction_calls;
...
void SomeFunction()
{
if (SomeFunction_calls < N) {
...
}
...
}
};
In this case, a MyClass<4> will have special treatment for the first 4 calls to SomeFunction(), a MyClass<4444444444444444444> will have special treatment for the first 4,444,444,444,444,444,444 calls, and so on. The counter will default to uint64_t, as that should be large enough to hold the value; when only a smaller number of calls need special treatment, you can specify a smaller type, such as MyClass<4, uint8_t> or MyClass<444444444, uint32_t>.
In C++ you can use the static keyword in a local variable context to create the object only once at the first call:
#include <iostream>
struct MyObject {
MyObject() {
std::cout << "Creating instance " << this << "\n";
};
};
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
int main(int argc, const char *argv[]) {
std::cout << "About to call foo...\n";
foo();
std::cout << "... second call ...\n";
foo();
std::cout << "... third call ...\n";
foo();
return 0;
}
With the above code you will notice that only on object MyObject will be created, on the first call to foo.
Note that if your function is a template then for each instantiation of the template you will get another distinct static variable. For example with:
template<int N>
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
the all the calls to foo<1>() will use the same variable but calling instead foo<2>() will access another copy of the function (another instantiation of the function template), that will have its own distinct static variable created on the first call to foo<2>(). All static variables that have been initialized will be destroyed after the end of main when the program terminates.

Function pointer delclaration in c++

I have written a class Seat in cpp & I declared a function pointer it it.
class implimentation is given below
Seat.cpp
#include "StdAfx.h"
#include "Seat.h"
int Seat::count = FL;
Seat::Seat(void)
{
seatId = Seat::count;
seatStatus = unoccupied;
Seat::count++;
}
Seat::~Seat(void)
{
}
void Seat::*checkSeatStatus(void)
{
}
Seat.h
#include <string>
using namespace std;
class Seat :
public Vehicle
{
int seatId;
int seatStatus;
static int count;
public:
Seat(void);
~Seat(void);
void (*checkSeatStatus)();
};
it showing error at function pointer declaration :
'checkSeatStatus' : illegal use of type 'void'
What is the reason behind ? , does it need any initialization of function pointer ?
If checkSeatStatus is intended to be a member function it should be:
void* Seat::checkSeatStatus(void) {
...
}
with function prototype within the class declaration of:
void* checkSeatStatus(void);
If it's intended to be a member variable holding a function pointer that you can set then, umm, don't do that... It's very probably the wrong design.
If (per the name) it's just supposed to return the current value of status then it should be a function that returns an int instead of a void *:
int Seat::checkStatus(void) {
return status;
}
NB: I removed Seat from the method name since it should be implicit from the fact that you called it on a Seat object.
This doesn't answer the question you ask, but will show how to use the function in a thread.
Using std::thread it's actually very easy to start a thread using any member function. The important part is that it should be a normal member function, so declared like
class Seat
{
...
public:
...
void checkSeatStatus();
};
Then to create a thread using the function you first need an instance of the class:
Seat seat;
And then you simply create the thread
std::thread my_thread{&Seat::checkSeatStatus, seat};
Do whatever other processing you want to do in the main thread, and then join the thread you had created:
my_thread.join();
There are a couple of important things to know here: The instance of the Seat class (the variable seat above) must live longer than the thread. If it goes out of scope and is destructed before the end of the thread that will lead to undefined behavior.
You must also join the tread before the thread-object (the variable my_thread above) is destructed.

Trouble implementing min Heaps in C++

I'm trying to implement a minheap in C++. However the following code keeps eliciting errors such as :
heap.cpp:24:4: error: cannot convert 'complex int' to 'int' in assignment
l=2i;
^
heap.cpp:25:4: error: cannot convert 'complex int' to 'int' in assignment
r=2i+1;
^
heap.cpp: In member function 'int Heap::main()':
heap.cpp:47:16: error: no matching function for call to 'Heap::heapify(int [11], int&)'
heapify(a,i);
^
heap.cpp:47:16: note: candidate is:
heap.cpp:21:5: note: int Heap::heapify(int)
int heapify(int i) //i is the parent index, a[] is the heap array
^
heap.cpp:21:5: note: candidate expects 1 argument, 2 provided
make: * [heap] Error 1
#include <iostream>
using namespace std;
#define HEAPSIZE 10
class Heap
{
int a[HEAPSIZE+1];
Heap()
{
for (j=1;j<(HEAPISZE+1);j++)
{
cin>>a[j];
cout<<"\n";
}
}
int heapify(int i) //i is the parent index, a[] is the heap array
{
int l,r,smallest,temp;
l=2i;
r=2i+1;
if (l<11 && a[l]<a[i])
smallest=l;
else
smallest=i;
if (r<11 && a[r]<a[smallest])
smallest=r;
if (smallest != i)
{
temp = a[smallest];
a[smallest] = a[i];
a[i]=temp;
heapify(smallest);
}
}
int main()
{
int i;
for (i=1;i<=HEAPSIZE;i++)
{
heapify(a,i);
}
}
}
Ultimately, the problem with this code is that it was written by someone who skipped chapters 1, 2 and 3 of "C++ for Beginners". Lets start with some basics.
#include <iostream>
using namespace std;
#define HEAPSIZE 10
Here, we have included the C++ header for I/O (input output). A fine start. Then, we have issued a directive that says "Put everything that is in namespace std into the global namespace". This saves you some typing, but means that all of the thousands of things that were carefully compartmentalized into std:: can now conflict with names you want to use in your code. This is A Bad Thing(TM). Try to avoid doing it.
Then we went ahead and used a C-ism, a #define. There are times when you'll still need to do this in C++, but it's better to avoid it. We'll come back to this.
The next problem, at least in the code you posted, is a misunderstanding of the C++ class.
The 'C' language that C++ is based on has the concept of a struct for describing a collection of data items.
struct
{
int id;
char name[64];
double wage;
};
It's important to notice the syntax - the trailing ';'. This is because you can describe a struct and declare variables of it's type at the same time.
struct { int id; char name[64]; } earner, manager, ceo;
This declares a struct, which has no type name, and variables earner, manager and ceo of that type. The semicolon tells the compiler when we're done with this statement. Learning when you need a semicolon after a '}' takes a little while; usually you don't, but in struct/class definition you do.
C++ added lots of things to C, but one common misunderstanding is that struct and class are somehow radically different.
C++ originally extended the struct concept by allowing you to describe functions in the context of the struct and by allowing you to describe members/functions as private, protected or public, and allowing inheritance.
When you declare a struct, it defaults to public. A class is nothing more than a struct which starts out `private.
struct
{
int id;
char name[64];
double wage;
};
class
{
public:
int id;
char name[64];
double wage;
};
The resulting definitions are both identical.
Your code does not have an access specifier, so everything in your Heap class is private. The first and most problematic issue this causes is: Nobody can call ANY of your functions, because they are private, they can only be called from other class members. That includes the constructor.
class Foo { Foo () {} };
int main()
{
Foo f;
return 0;
}
The above code will fail to compile, because main is not a member of Foo and thus cannot call anything private.
This brings us to another problem. In your code, as posted, main is a member of Foo. The entry point of a C++ program is main, not Foo::main or std::main or Foo::bar::herp::main. Just, good old int main(int argc, const char* argv[]) or int main().
In C, with structs, because C doesn't have member functions, you would never be in a case where you were using struct-members directly without prefixing that with a pointer or member reference, e.g. foo.id or ptr->wage. In C++, in a member function, member variables can be referenced just like local function variables or parameters. This can lead to some confusion:
class Foo
{
int a, b;
public:
void Set(int a, int b)
{
a = a; // Erh,
b = b; // wat???
}
};
There are many ways to work around this, but one of the most common is to prefix member variables with m_.
Your code runs afoul of this, apparently the original in C passed the array to heapify, and the array was in a local variable a. When you made a into a member, leaving the variable name exactly the same allowed you not to miss the fact that you no-longer need to pass it to the object (and indeed, your heapify member function no-longer takes an array as a pointer, leading to one of your compile errors).
The next problem we encounter, not directly part of your problem yet, is your function Heap(). Firstly, it is private - you used class and haven't said public yet. But secondly, you have missed the significance of this function.
In C++ every struct/class has an implied function of the same name as the definition. For class Heap that would be Heap(). This is the 'default constructor'. This is the function that will be executed any time someone creates an instance of Heap without any parameters.
That means it's going to be invoked when the compiler creates a short-term temporary Heap, or when you create a vector of Heap()s and allocate a new temporary.
These functions have one purpose: To prepare the storage the object occupies for usage. You should try and avoid as much other work as possible until later. Using std::cin to populate members in a constructor is one of the most awful things you can do.
We now have a basis to begin to write the outer-shell of the code in a fashion that will work.
The last change is the replacement of "HEAPSIZE" with a class enum. This is part of encapsulation. You could leave HEAPSIZE as a #define but you should expose it within your class so that external code doesn't have to rely on it but can instead say things like Heap::Size or heapInstance.size() etc.
#include <iostream>
#include <cstdint> // for size_t etc
#include <array> // C++11 encapsulation for arrays.
struct Heap // Because we want to start 'public' not 'private'.
{
enum { Size = 10 };
private:
std::array<int, Size> m_array; // meaningful names ftw.
public:
Heap() // default constructor, do as little as possible.
: m_array() // says 'call m_array()s default ctor'
{}
// Function to load values from an istream into this heap.
void read(std::istream& in)
{
for (size_t i = 0; i < Size; ++i)
{
in >> m_array[i];
}
return in;
}
void write(std::ostream& out)
{
for (size_t i = 0; i < Size; ++i)
{
if (i > 0)
out << ','; // separator
out << m_array[i];
}
}
int heapify(size_t index)
{
// implement your code here.
}
}; // <-- important.
int main(int argc, const char* argv[])
{
Heap myHeap; // << constructed but not populated.
myHeap.load(std::cin); // read from cin
for (size_t i = 1; i < myHeap.Size; ++i)
{
myHeap.heapify(i);
}
myHead.write(std::cout);
return 0;
}
Lastly, we run into a simple, fundamental problem with your code. C++ does not have implicit multiplication. 2i is the number 2 with a suffix. It is not the same as 2 * i.
int l = 2 * i;
There is also a peculiarity with your code that suggests you are mixing between 0-based and 1-based implementation. Pick one and stick with it.
--- EDIT ---
Technically, this:
myHeap.load(std::cin); // read from cin
for (size_t i = 1; i < myHeap.Size; ++i)
{
myHeap.heapify(i);
}
is poor encapsulation. I wrote it this way to draw on the original code layout, but I want to point out that one reason for separating construction and initialization is that it allows initialization to be assured that everything is ready to go.
So, it would be more correct to move the heapify calls into the load function. After all, what better time to heapify than as we add new values, keeping the list in order the entire time.
for (size_t i = 0; i < Size; ++i)
{
in >> m_array[i];
heapify(i);
}
Now you've simplified your classes api, and users don't have to be aware of the internal machinery.
Heap myHeap;
myHeap.load(std::cin);
myHeap.write(std::cout);

Define constructor of a class inside a namespace

I am fairly new to C++ so this may be an easy one.
I created a namespace and inside that namespace is a class. I cannot figure out how to define any of my class's constructors without receiving errors.
#include <iostream>
namespace bill {
const char * null ="EMPTY";
const int MAX_STACK_SIZE = 100;
class myStackClass {
private:
int i;
public:
myStackClass();
myStackClass(int[], int);
int peek();
int pop();
int push(int insertMe);
const char empty[5];
};
}
using namespace bill;
bill::myStackClass::myStackClass() //bill::myStackClass() doesn't work either
:
i(0)
{ //error C2448: 'i' : function-style initializer appears to be a function definition
} //"bill::myStackClass::myStackClass()" provides no initializer for:
const member "bill::myStackClass::empty"
bill::myStackClass::myStackClass(int[],int)
{ //error C2439: 'bill::myStackClass::empty' : member could not be initialized
} //"bill::myStackClass::myStackClass(int *, int)" provides no initializer for:
const member "bill::myStackClass::empty"
int bill::myStackClass::peek() // I am able to call methods belonging to the class
{
}
I'm sorry if any of this information is cluttered and hard to read or just downright not helpful. I have been reading my textbook and googling errors for hours and would really appreciate some insight. Thank you.
It's a bit difficult to decipher what you're looking for, as your stack class isn't much of a stack. That said, just to get it to compile without warnings, you have to initialize your empty class member in the constructor initializer list, as you've declared it to be const.
e.g. if you have your constructors as:
bill::myStackClass::myStackClass()
: i(0), empty {}
{}
bill::myStackClass::myStackClass(int[],int)
: empty{}
{}
This will initialize your empty char array to be, well, empty. If you wanted it to contain something, then you could specify it in within the curly brackets, e.g.
bill::myStackClass::myStackClass()
: i(0), empty {'H', 'E', 'L', 'L', 'O'}
{
std::cout << empty << std::endl;
}
then creating an object of your class (via the no-arg constructor) will print HELLO
bill::myStackClass stk; //--> prints HELLO
I should also make note that the use of uniform initializers (the curly-braces) is a C++11 feature, so depending on your compiler, you might have to supply an extra flag (i.e. -std=c++11)
You don't need to say using namespace bill if you are already pre-pending bill:: to your method definitions (which in your posted code, you are). The using namespace bill makes it such that the bill namespace is searched when resolving your identifier names, but if you're explicitly stating them to be bill within the bill namespace (via the bill::), then this isn't needed.
Also, the default scoping for a class if private, so it's redundant to specify the first part of a classes members to be private like that.

Static member function pointer to hold non static member function

This has defeated me. I want to have a static class variable which is a pointer to a (non-static) member function. I've tried all sorts of ways, but with no luck (including using typedefs, which just seemed to give me a different set of errors). In the code below I have the static class function pointer funcptr, and I can call it successfully from outside the class, but not from within the member function CallFuncptr - which is what I want to do. Any suggestions?
#include <stdio.h>
class A
{
public:
static int (A::*funcptr)();
int Four() { return 4;};
int CallFuncptr() { return (this->*funcptr)(); }
// doesn't link - undefined reference to `A::funcptr'
};
int (A::*funcptr)() = &A::Four;
int main()
{
A fred;
printf("four? %d\n", (fred.*funcptr)()); // This works
printf("four? %d\n", fred.CallFuncptr()); // But this is the way I want to call it
}
Try this instead:
#include <iostream>
class A {
public:
typedef int (A::*AMemFn)();
static AMemFn funcptr;
int Four() { return 4; }
int CallFuncptr() { return (this->*funcptr)(); }
};
A::AMemFn A::funcptr = &A::Four;
int main()
{
A fred;
std::cout << "four? " << fred.CallFuncptr() << std::endl;
}
jweyrich has a nice looking work around (and I suggest you use it), but I thought I'd elaborate on what the real problem in the code is:
Your problem is this line:
int (A::*funcptr)() = &A::Four;
This is defining a global variable called funcptr that is of the right type, rather than A::funcptr.
What you need is this mess:
int (A::*(A::funcptr))() = &A::Four;
This ugly mess is why I suggest you go down the typedef path to get a nice looking version like jweyrich's solution.
A static variable is not a member of a particular object -- it can only be accessed through the classes namespace. CallFuncptr should be rewritten:
int CallFuncptr() { return (*funcptr)();
which I think should work, since this function can access functions in A's namespace without specifying it.
Also, function pointers are more of a C construct than C++. You can access the static variable outside the class with the code:
A::CallFuncptr
since CallFunctptr just resides in A's namespace