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
Yes I have read a lot of tutorials and questions and also tried a lot of combinations but it seems not to work.
My goal is not to use dynamic allocation.
My classes look like this:
Pages
Page
PMain:Page
PCam:Page
on my main when I do this:
1.
main:
Page * page;
PCam main;
main.setContext(context);
page = &main;
page->echo();
result: PCam
but when I try to create the instance inside an outside class and point it to page it fails.
2.
pages class:
Pages::Pages(Page*& page, Context& context){
this->context = &context;
PMain main;
main.setContext(*this->context);
main.echo();
// page = &main; <---
}
main:
Page * page;
Pages pages(page, context);
page->echo();
result: Page
expected result: PCam
My classes:
Page:
void Page::setContext(Context & context)
{
this->context = &context;
}
void Page::echo() //virtual
{
std::cout << "echo Page" << std::endl;
}
PMain:
void PMain::echo(){
std::cout << "echo PMain" << std::endl;}
}
PCam:
void PCam::echo(){
std::cout << "echo PCam" << std::endl;}
}
Any help would be appreciated. thanks.
Your problem, or one of them, is that this:
Pages::Pages(Page*& page, Context& context){
[...]
PMain main;
is a local stack variable. When this function returns, it ceases to exist.
If you've assigned it to a pointer, you'll get undefined behavior by using it.
My goal is not to use dynamic allocation.
Unless you have some specific reason, this is a mostly pointless goal. If you want a pointer to a stack object (i.e., one that's not dynamically allocated), that object must remain in scope as long as you use the pointer. If you can't do that, then you need to put it on the heap (i.e., dynamically allocate).
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 19 days ago.
This post was edited and submitted for review 18 days ago and failed to reopen the post:
Needs details or clarity Add details and clarify the problem by editing this post.
Improve this question
Have function:
void btCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
// ...
}
Need to use in:
BT.register_callback(btCallback);
Compiler error:
no known conversion for argument 1 from 'void(esp_spp_cb_event_t, esp_spp_cb_param_t*)' to 'void (**)(esp_spp_cb_event_t, esp_spp_cb_param_t*)'
As I understand it, he needs a pointer to function pointer. I don't know how to create it. I tried a function pointer (through &), does not fit.
Reproduction (PlatformIO / platform: espressif32, board: esp-wrover-kit, framework: arduino):
#include <Arduino.h>
#include <BluetoothSerial.h>
BluetoothSerial BT;
void btCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
Serial.println("TEST");
}
void setup() {
Serial.begin(115200);
BT.begin("", true);
BT.register_callback(btCallback);
BT.connect("TEST");
}
void loop() { }
P.S. Is arduino-esp32 BluetoothSerial::register_callback function.
You need to make a pointer variable, and then take a pointer from it using the & operator.
void f()
{
// ...
}
void g(void (**p)())
{
// ...
}
int main()
{
void (*f_ptr)() = f;
g(&f_ptr);
}
Try if here.
As I understand it, he needs a pointer to function pointer. I don't
know how to create it. I tried a function pointer (through &), does
not fit.
In the previous example, taking &f doesn't have any effect. These two lines are equivalent!:
void (*f_ptr)() = f;
void (*f_ptr)() = &f;
Therefore, if you were doing:
g(&f);
you are actually passing a simple function pointer, not a pointer to function pointer.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am building a project that is composed of Vehicle, Showroom, and Dealership. I've built the classes, and I am testing out my method GetAveragePrice()
float Dealership::GetAveragePrice()
This method was working perfectly:
Dealership dealership("COP3503 Vehicle Emporium", 3);
dealership.AddShowroom(&showroom);
dealership.AddShowroom(&secondary);
dealership.AddShowroom(&third);
cout << "Using just the GetAveragePrice() function\n\n";
cout << "Average price of the cars in the dealership: $" << std::fixed << std::setprecision(2);
cout << dealership.GetAveragePrice();
The output would be
Using just the GetAveragePrice() function
Average price of the cars in the dealership: $27793.60
This is the expected output I wanted, but I was told I have memory leaks and must include a destructor to deallocate my *Showroom showroomList pointer (which I initialized as the following in the Dealership constructor):
this->showroomList = new Showroom[maxNumOfShowrooms];
So I write my destructor as the following:
Dealership::~Dealership()
{
delete [] showroomList;
}
Now, there aren't any memory leaks, but I don't get the expected output and an exit code 11:
Using just the GetAveragePrice() function
Process finished with exit code 11
Does anyone know why this destructor is messing up my output?
This version would delete only once by the last instance standing, in its destructor.
std::unique_ptr<ShowRoom> Dealership::showroomList;
Dealership::Dealership(size_t maxNumOfShowrooms)
:showroomList(std::unique_ptr<ShowRoom>(new Showroom[maxNumOfShowrooms]))
{
}
Dealership::~Dealership()
{
// auto deleted here, with reverse order of initialization
}
but you have a new and delete pair so you should check for deletion only once. This would need some global counter outside of class (or its static variable) and this may not be as readable as smart pointer.
If you are using multiple threads with this, then you could be better with shared_ptr and a custom deleter ([](T * ptr){delete [] ptr;}) as its second constructor parameter.
At least this way you can know if error is about new and delete.
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 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}
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 7 years ago.
Improve this question
coming from java i would like to not have to deal with de-allocation when creating new custom or other library's objects.
today i was trying to create an instance of my entity object like:
entity cube = new entity("entityName")
because this is how entity's constructor is formatted
but i get the following error:
cannot convert from |entity *| to |entity|
i noticed there are no errors if i just remove the new keyword, and i was wondering two things.
what does the error while using new mean ? (i'm pretty confident with how pointers work but not completely as i started with java.)
is it ok for me to create objects like that without the new keyword or is an object even created? (because there are no errors.)
new entity("entityName")
means "create an instance of entity in the free store and return a pointer to that instance".
Since a pointer to an entity is not the same as an entity, you cannot initialise an entity with that value unless you have yet another constructor.
The way to do what you want is
entity cube("entityname");
And you need a good book on C++.
First, I suggest you to read a C++ tutorial. It has much more complexity than Java.
This is a very partial Java to C++ "how to convert" guide that I can give you:
Java code:
void sayHello(String name) {
system.out.println("Hello, " + name);
}
public static void main(String args[]) {
String name = "James"; // <-- This string is of course created in the dynamic memory
sayHello(name); // <-- "name" will be passed by reference to the "sayHello()" method
}
Equivalent in C++ - option 1:
void sayHello(const std::string &name) {
std::cout << "Hello, " << name << std::endl;
}
int main() {
std::string name("James"); // <-- Variable is created on the stack
sayHello(name); // <-- Although "name" is not a pointer, it will be passed by reference to "sayHello", as "name" is defiend there with "&", which means that it is a reference
}
A reference is a very "weird" type - it behaves like a local variable, although it actually points to an instance that does not have to be on the stack of the current function or on the stack at all.
C++ - option 2:
void sayHello(const std::string *name) {
std::cout << "Hello, " << *name << std::endl; // <-- dereferenceing "name" using a preceding star, as "cout" needs the variable itself and not its address
}
int main() {
std::string *name = new std::string("James"); // <-- Instance is created in the dynamic memory
sayHello(name); // <-- Sending the pointer "name" to the "sayHello" function
// You will need to free "name" somewhere in the code unless you don't care about memory leaks
}
There are more options, like passing the instance by value (not recommended in such case), or like creating it in the dynamic memory and deref
what does the error while using new mean ? (i'm pretty confident with how pointers work but not completely as i started with java.)
No. C++ is different about this, you don't use an allocation (new) to initialize cube:
entity cube("entityName");
is it ok for me to create objects like that without the new keyword or is an object even created? (because there are no errors.)
No. See above. ("because there are no errors." I doubt this, there should at least be compiler warnings if you assign entity from a pointer.)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
How do I have main() remember the value of a variable each time it is called?
i.e. if I run this program the first time I want mainCallCounter = 0, but when I is called again I want it to increase the counter
#include <iostream>
using namespace std;
static int mainCallCounter = 0;
void outputMainCallCount()
{
cout << "Main was called" << mainCallCounter << "times." << endl;
}
int main()
{
outputMainCallCount();
mainCallCounter++;
return 0;
Main is the entry point for your program. Main is called once (normally) and, when it exits, your program is torn down and cleaned up.
Obviously this means a local variable will be insufficient. You need some sort of external storage which persists longer than your application, i.e., the file system.
You can't. Each run of a program is independent. You will need to save mainCallCounter somewhere and re-read it the next time the application launches. Writing it into a file is one option, another might be something like the Windows registry or Mac OS X defaults system, etc.
All variables declared in C++ expire when the program ends. If you want to persistently remember how many times the program has been run, you will need to store that data in an external file and update it whenever you run the program.
For example:
#include <iostream>
#include <fstream>
int numTimesRun() {
std::ifstream input("counter.txt"); // assuming it exists
int numTimesRun;
input >> numTimesRun;
return numTimesRun;
}
void updateCounter() {
int counter = numTimesRun();
std::ofstream output("counter.txt");
output << counter;
}
int main() {
int timesRun = numTimesRun();
updateCounter();
/* ... */
}
Hope this helps!